Skip to content

Commit

Permalink
fix(pickOne): return undefined on empty array
Browse files Browse the repository at this point in the history
  • Loading branch information
jordan-boyer committed Oct 11, 2023
1 parent 9ec34cc commit e18d506
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 3 deletions.
3 changes: 1 addition & 2 deletions src/array-pick-one.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,5 @@
* @returns item like : "pine"
*/
export function pickOne<T> (items: T[]) {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return items[Math.floor(Math.random() * items.length)] as T
return items[Math.floor(Math.random() * items.length)]
}
4 changes: 3 additions & 1 deletion tests/arrays.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ const elementsShuffled = shuffleArray(elements)
it('shuffle an array does not affect the original one', () => { expect(elementsShuffled).not.toStrictEqual(elements) })

const elementPicked = pickOne(elements)
it('pick one returns an element from the array', () => { expect(elementPicked && elements.includes(elementPicked)).toStrictEqual(true) })
const isUndefinedPicked = pickOne([false].filter(Boolean))
it('pick one returns an element from the array', () => { expect(elementPicked !== undefined && elements.includes(elementPicked)).toStrictEqual(true) })
it('pick one returns undefined', () => { expect(isUndefinedPicked).toBeUndefined() })

it('array unique A', () => { expect(arrayUnique([1, 1, 2, 1, 1, 3, 1])).toStrictEqual([1, 2, 3]) })
it('array unique B', () => { expect(arrayUnique(['plop', 'plop', 2, 'plop', 'plop', 3, 'plop'])).toStrictEqual(['plop', 2, 3]) })
Expand Down

0 comments on commit e18d506

Please sign in to comment.