Skip to content

Commit f2ff93d

Browse files
committed
fix(sample): include "undefined" in return union type
1 parent 4478e33 commit f2ff93d

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

src/array/sample.spec.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,19 @@
1-
import { describe, expect, it } from 'vitest';
1+
import { assert, describe, expect, it } from 'vitest';
22
import { sample } from './sample';
33

44
describe('sample', () => {
55
it('selects a random element from an array', () => {
66
const arr = [1, 2, 3, 4, 5];
77

8-
expect(arr.includes(sample(arr))).toBe(true);
8+
const randomElement = sample(arr);
9+
10+
assert(randomElement !== undefined);
11+
expect(arr.includes(randomElement)).toBe(true);
12+
});
13+
14+
it('returns undefined when given array is empty', () => {
15+
const arr: number[] = [];
16+
17+
expect(sample(arr)).toBe(undefined);
918
});
1019
});

src/array/sample.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
* const randomElement = sample(array);
1313
* // randomElement will be one of the elements from the array, selected randomly.
1414
*/
15-
export function sample<T>(arr: readonly T[]): T {
15+
export function sample<T>(arr: readonly T[]): T | undefined {
1616
const randomIndex = Math.floor(Math.random() * arr.length);
1717
return arr[randomIndex];
1818
}

0 commit comments

Comments
 (0)