diff --git a/packages/stdlib/src/arrays/first/index.test.ts b/packages/stdlib/src/arrays/first/index.test.ts new file mode 100644 index 0000000..74a0062 --- /dev/null +++ b/packages/stdlib/src/arrays/first/index.test.ts @@ -0,0 +1,23 @@ +import { describe, it, expect } from 'vitest'; +import { first } from '.'; + +describe('first', () => { + it('return the first element of a non-empty array', () => { + expect(first([1, 2, 3])).toBe(1); + expect(first(['a', 'b', 'c'])).toBe('a'); + }); + + it('return undefined for an empty array without a default value', () => { + expect(first([])).toBeUndefined(); + }); + + it('return the default value for an empty array with a default value', () => { + expect(first([], 42)).toBe(42); + expect(first([], 'default')).toBe('default'); + }); + + it('return the first element even if a default value is provided', () => { + expect(first([1, 2, 3], 42)).toBe(1); + expect(first(['a', 'b', 'c'], 'default')).toBe('a'); + }); +}); \ No newline at end of file diff --git a/packages/stdlib/src/arrays/first/index.ts b/packages/stdlib/src/arrays/first/index.ts new file mode 100644 index 0000000..720bb8a --- /dev/null +++ b/packages/stdlib/src/arrays/first/index.ts @@ -0,0 +1,20 @@ +/** + * @name first + * @category Arrays + * @description Returns the first element of an array + * + * @param {Value[]} arr The array to get the first element from + * @param {Value} [defaultValue] The default value to return if the array is empty + * @returns {Value | undefined} The first element of the array, or the default value if the array is empty + * + * @example + * first([1, 2, 3]); // => 1 + * + * @example + * first([]); // => undefined + * + * @since 0.0.3 + */ +export function first(arr: Value[], defaultValue?: Value) { + return arr[0] ?? defaultValue; +} \ No newline at end of file