diff --git a/packages/cli-kit/src/public/common/array.test.ts b/packages/cli-kit/src/public/common/array.test.ts index 720becbac0b..8804f44839a 100644 --- a/packages/cli-kit/src/public/common/array.test.ts +++ b/packages/cli-kit/src/public/common/array.test.ts @@ -1,4 +1,4 @@ -import {difference, uniq, uniqBy} from './array.js' +import {difference, takeRandomFromArray, uniq, uniqBy} from './array.js' import {describe, test, expect} from 'vitest' describe('uniqBy', () => { @@ -62,3 +62,38 @@ describe('difference', () => { expect(got).toEqual([1]) }) }) + +describe('takeRandomFromArray', () => { + test('returns a random element from the array', () => { + // Given + const array = [1, 2, 3, 4, 5] + + // When + const got = takeRandomFromArray(array) + + // Then + expect(array).toContain(got) + }) + + test('returns undefined for an empty array', () => { + // Given + const array: number[] = [] + + // When + const got = takeRandomFromArray(array) + + // Then + expect(got).toBeUndefined() + }) + + test('handles arrays with a single element', () => { + // Given + const array = ['only'] + + // When + const got = takeRandomFromArray(array) + + // Then + expect(got).toBe('only') + }) +}) diff --git a/packages/cli-kit/src/public/common/array.ts b/packages/cli-kit/src/public/common/array.ts index 8b22c0b7b93..335393f8cbe 100644 --- a/packages/cli-kit/src/public/common/array.ts +++ b/packages/cli-kit/src/public/common/array.ts @@ -9,7 +9,19 @@ import type {List, ValueIteratee} from 'lodash' * @returns A random element from the array. */ export function takeRandomFromArray(array: T[]): T { - return array[Math.floor(Math.random() * array.length)]! + if (array.length === 0) { + return undefined as T + } + const arrayLength = array.length + const maxUint32 = 0xffffffff + const limit = maxUint32 - (maxUint32 % arrayLength) + const buffer = new Uint32Array(1) + let randomNumber: number + do { + globalThis.crypto.getRandomValues(buffer) + randomNumber = buffer[0]! + } while (randomNumber >= limit) + return array[randomNumber % arrayLength]! } /**