From 759d418d888c3fc2e116f2f4de404248ebb428af Mon Sep 17 00:00:00 2001 From: robonen Date: Thu, 24 Oct 2024 07:28:15 +0700 Subject: [PATCH] feat(packages/stdlib): add last arrays util --- packages/stdlib/src/arrays/last/index.test.ts | 23 +++++++++++++++++++ packages/stdlib/src/arrays/last/index.ts | 20 ++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 packages/stdlib/src/arrays/last/index.test.ts create mode 100644 packages/stdlib/src/arrays/last/index.ts diff --git a/packages/stdlib/src/arrays/last/index.test.ts b/packages/stdlib/src/arrays/last/index.test.ts new file mode 100644 index 0000000..9f9ce60 --- /dev/null +++ b/packages/stdlib/src/arrays/last/index.test.ts @@ -0,0 +1,23 @@ +import { describe, it, expect } from 'vitest'; +import { last } from '.'; + +describe('last', () => { + it('return the last element of a non-empty array', () => { + expect(last([1, 2, 3, 4, 5])).toBe(5); + expect(last(['a', 'b', 'c'])).toBe('c'); + }); + + it('return undefined if the array is empty and no default value is provided', () => { + expect(last([])).toBeUndefined(); + }); + + it('return the default value for an empty array with a default value', () => { + expect(last([], 42)).toBe(42); + expect(last([], 'default')).toBe('default'); + }); + + it('return the first element even if a default value is provided', () => { + expect(last([1, 2, 3], 42)).toBe(3); + expect(last(['a', 'b', 'c'], 'default')).toBe('c'); + }); +}); \ No newline at end of file diff --git a/packages/stdlib/src/arrays/last/index.ts b/packages/stdlib/src/arrays/last/index.ts new file mode 100644 index 0000000..4661aaf --- /dev/null +++ b/packages/stdlib/src/arrays/last/index.ts @@ -0,0 +1,20 @@ +/** + * @name last + * @section Arrays + * @description Gets the last element of an array + * + * @param {Value[]} arr The array to get the last element of + * @param {Value} [defaultValue] The default value to return if the array is empty + * @returns {Value | undefined} The last element of the array, or the default value if the array is empty + * + * @example + * last([1, 2, 3, 4, 5]); // => 5 + * + * @example + * last([], 3); // => 3 + * + * @since 0.0.3 + */ +export function last(arr: Value[], defaultValue?: Value) { + return arr[arr.length - 1] ?? defaultValue; +}