From f2ff93d1d67e91fcd514f9f220d764a61371192e Mon Sep 17 00:00:00 2001 From: Christian Rackerseder Date: Fri, 8 Aug 2025 09:07:22 +0200 Subject: [PATCH] fix(sample): include "undefined" in return union type --- src/array/sample.spec.ts | 13 +++++++++++-- src/array/sample.ts | 2 +- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/array/sample.spec.ts b/src/array/sample.spec.ts index 626ccf96e..5e891a353 100644 --- a/src/array/sample.spec.ts +++ b/src/array/sample.spec.ts @@ -1,10 +1,19 @@ -import { describe, expect, it } from 'vitest'; +import { assert, describe, expect, it } from 'vitest'; import { sample } from './sample'; describe('sample', () => { it('selects a random element from an array', () => { const arr = [1, 2, 3, 4, 5]; - expect(arr.includes(sample(arr))).toBe(true); + const randomElement = sample(arr); + + assert(randomElement !== undefined); + expect(arr.includes(randomElement)).toBe(true); + }); + + it('returns undefined when given array is empty', () => { + const arr: number[] = []; + + expect(sample(arr)).toBe(undefined); }); }); diff --git a/src/array/sample.ts b/src/array/sample.ts index 1c22fd9b0..0aba56bcb 100644 --- a/src/array/sample.ts +++ b/src/array/sample.ts @@ -12,7 +12,7 @@ * const randomElement = sample(array); * // randomElement will be one of the elements from the array, selected randomly. */ -export function sample(arr: readonly T[]): T { +export function sample(arr: readonly T[]): T | undefined { const randomIndex = Math.floor(Math.random() * arr.length); return arr[randomIndex]; }