Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion packages/cli-kit/src/public/common/array.test.ts
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand Down Expand Up @@ -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')
})
})
14 changes: 13 additions & 1 deletion packages/cli-kit/src/public/common/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,19 @@ import type {List, ValueIteratee} from 'lodash'
* @returns A random element from the array.
*/
export function takeRandomFromArray<T>(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]!
}

/**
Expand Down
Loading