From 4a190c52b9170622e015ab47de629c4fd8436346 Mon Sep 17 00:00:00 2001 From: Sonam Serchan Date: Sat, 29 Jul 2023 19:42:33 +1000 Subject: [PATCH] use built-in Node module - crypto --- src/slack/slackInteraction.ts | 4 ++-- src/utils/getRandomValue.test.ts | 13 +++++++++++++ src/utils/getRandomValue.ts | 6 ++++++ 3 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 src/utils/getRandomValue.test.ts create mode 100644 src/utils/getRandomValue.ts diff --git a/src/slack/slackInteraction.ts b/src/slack/slackInteraction.ts index 0f9a8ab..4439a72 100644 --- a/src/slack/slackInteraction.ts +++ b/src/slack/slackInteraction.ts @@ -2,6 +2,7 @@ import { ChatPostMessageArguments, ErrorCode } from "@slack/web-api"; import { SlackWebClient } from "../helpers/types"; import { getEmojisToReactWith } from "../emojis/emojiHandler"; import SLACK_MESSAGE_BLOCKS from "../helpers/files/welcomeMessageBlocks.json"; +import { getRandomValue } from "../utils/getRandomValue"; export async function addReactionToSlackPost( emoji: string, @@ -121,8 +122,7 @@ export async function handleSlackJoinEvent( userId: string ): Promise { const messages = SLACK_MESSAGE_BLOCKS.welcomeMessageBlocks; - const welcomeMessage = - messages[Math.floor(Math.random() * messages.length)]; + const welcomeMessage = messages[getRandomValue({ range: messages.length })]; // substitute user id in random welcome message with real user id const welcomeMessageText = welcomeMessage.blocks[0].text.text .split("@userId") diff --git a/src/utils/getRandomValue.test.ts b/src/utils/getRandomValue.test.ts new file mode 100644 index 0000000..b994bd3 --- /dev/null +++ b/src/utils/getRandomValue.test.ts @@ -0,0 +1,13 @@ +import { getRandomValue } from "./getRandomValue"; + +describe("Get random value", () => { + it("should return random int value from 0-2 provided range 3", () => { + const randomValue = getRandomValue({ range: 3 }); + expect([0, 1, 2].includes(randomValue)).toBe(true); + }); + + it("should return random int value from 0-4 provided range 5", () => { + const randomValue = getRandomValue({ range: 5 }); + expect([0, 1, 2, 3, 4].includes(randomValue)).toBe(true); + }); +}); diff --git a/src/utils/getRandomValue.ts b/src/utils/getRandomValue.ts new file mode 100644 index 0000000..85f6f16 --- /dev/null +++ b/src/utils/getRandomValue.ts @@ -0,0 +1,6 @@ +import crypto from "crypto"; + +export const getRandomValue = ({ range }: { range: number }) => { + const array = new Uint32Array(1); // creates array with length only 1 + return crypto.getRandomValues(array)[0] % range; //thus accessing first position in the array +};