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
23 changes: 22 additions & 1 deletion packages/cli-kit/src/public/common/array.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,27 @@
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 undefined for an empty array', () => {
// When
const got = takeRandomFromArray([])

// Then
expect(got).toBeUndefined()
})

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)
})
})

describe('uniqBy', () => {
test('removes duplicates', () => {
// When
Expand Down
20 changes: 18 additions & 2 deletions packages/cli-kit/src/public/common/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,24 @@ import type {List, ValueIteratee} from 'lodash'
* @param array - Array from which we'll select a random item.
* @returns A random element from the array.
*/
export function takeRandomFromArray<T>(array: T[]): T {
return array[Math.floor(Math.random() * array.length)]!
export function takeRandomFromArray<T>(array: T[]): T | undefined {
if (array.length === 0) {
return undefined
}

// Rejection sampling to avoid modulo bias
const maxUint32 = 0xffffffff
const range = array.length
const limit = maxUint32 - (maxUint32 % range)

const randomBuffer = new Uint32Array(1)
let randomValue: number
do {
globalThis.crypto.getRandomValues(randomBuffer)
randomValue = randomBuffer[0]!
} while (randomValue >= limit)

return array[randomValue % range]
}

/**
Expand Down
Loading