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 an element from the array', () => {
// Given
const array = ['apple', 'banana', 'cherry']

// When
const got = takeRandomFromArray(array)

// Then
expect(array).toContain(got)
})

test('returns the only element from a single-element array', () => {
// Given
const array = ['apple']

// When
const got = takeRandomFromArray(array)

// Then
expect(got).toBe('apple')
})

test('returns undefined for an empty array', () => {
// Given
const array: string[] = []

// When
const got = takeRandomFromArray(array)

// Then
expect(got).toBeUndefined()
})
})
17 changes: 16 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,22 @@ 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)]!
const length = array.length
if (length === 0) {
return array[0]!
}

const arrayBuffer = new Uint32Array(1)
const maxUint32 = 4294967296
const maxMultiple = maxUint32 - (maxUint32 % length)

let randomValue: number
do {
globalThis.crypto.getRandomValues(arrayBuffer)
randomValue = arrayBuffer[0]!
} while (randomValue >= maxMultiple)

return array[randomValue % length]!
}

/**
Expand Down
Loading