diff --git a/packages/cli-kit/src/public/common/array.test.ts b/packages/cli-kit/src/public/common/array.test.ts index 720becbac0b..df6945e38a0 100644 --- a/packages/cli-kit/src/public/common/array.test.ts +++ b/packages/cli-kit/src/public/common/array.test.ts @@ -1,6 +1,30 @@ -import {difference, uniq, uniqBy} from './array.js' +import {difference, takeRandomFromArray, uniq, uniqBy} from './array.js' import {describe, test, expect} from 'vitest' +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() + }) +}) + describe('uniqBy', () => { test('removes duplicates', () => { // When diff --git a/packages/cli-kit/src/public/common/array.ts b/packages/cli-kit/src/public/common/array.ts index 8b22c0b7b93..234100487f9 100644 --- a/packages/cli-kit/src/public/common/array.ts +++ b/packages/cli-kit/src/public/common/array.ts @@ -9,7 +9,17 @@ 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 array[0]! + if (array.length === 1) return array[0]! + + const maxUint32 = 0xffffffff + const range = maxUint32 - (maxUint32 % array.length) + let randomValue: number + do { + randomValue = globalThis.crypto.getRandomValues(new Uint32Array(1))[0]! + } while (randomValue >= range) + + return array[randomValue % array.length]! } /**