Skip to content

Commit

Permalink
use built-in Node module - crypto
Browse files Browse the repository at this point in the history
  • Loading branch information
Sonam Serchan authored and sonam-serchan committed Aug 1, 2023
1 parent 14c97c9 commit 4a190c5
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/slack/slackInteraction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -121,8 +122,7 @@ export async function handleSlackJoinEvent(
userId: string
): Promise<void> {
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")
Expand Down
13 changes: 13 additions & 0 deletions src/utils/getRandomValue.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
6 changes: 6 additions & 0 deletions src/utils/getRandomValue.ts
Original file line number Diff line number Diff line change
@@ -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
};

0 comments on commit 4a190c5

Please sign in to comment.