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
16 changes: 15 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,20 @@
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 an element from the array', () => {
const array = [1, 2, 3]
const got = takeRandomFromArray(array)
expect(array).toContain(got)
})

test('returns undefined for an empty array', () => {
const array: number[] = []
const got = takeRandomFromArray(array)
expect(got).toBeUndefined()
})
})

describe('uniqBy', () => {
test('removes duplicates', () => {
// When
Expand Down
4 changes: 3 additions & 1 deletion packages/cli-kit/src/public/common/array.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import lodashUniqBy from 'lodash/uniqBy.js'
import lodashDifference from 'lodash/difference.js'
import {randomInt} from 'node:crypto'
import type {List, ValueIteratee} from 'lodash'

/**
Expand All @@ -9,7 +10,8 @@ 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 unknown as T
return array[randomInt(array.length)]!
}

/**
Expand Down
Loading