UNPKG

ts-data-forge

Version:

[![npm version](https://img.shields.io/npm/v/ts-data-forge.svg)](https://www.npmjs.com/package/ts-data-forge) [![npm downloads](https://img.shields.io/npm/dm/ts-data-forge.svg)](https://www.npmjs.com/package/ts-data-forge) [![License](https://img.shields.

74 lines (71 loc) 1.98 kB
import { none } from '../../functional/optional/impl/optional-none.mjs'; import { some } from '../../functional/optional/impl/optional-some.mjs'; import { pipe } from '../../functional/pipe.mjs'; import '@sindresorhus/is'; function at(...args) { switch (args.length) { case 2: { const [array, index$1] = args; return pipe(index$1 < 0 ? array.length + index$1 : index$1).map((normalizedIndex) => normalizedIndex < 0 || normalizedIndex >= array.length ? none : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion some(array[normalizedIndex])).value; } case 1: { const [index] = args; return (array) => at(array, index); } } } /** * Returns the first element of an array as an Optional. * * @example * * ```ts * const users = [{ id: 1 }, { id: 2 }]; * * const empty: { id: number }[] = []; * * const first = Arr.head(users); * * const none = Arr.head(empty); * * assert.deepStrictEqual(first, Optional.some({ id: 1 })); * * assert.deepStrictEqual(none, Optional.none); * ``` */ const head = (array) => // eslint-disable-next-line total-functions/no-unsafe-type-assertion (array.length === 0 ? none : some(array.at(0))); /** * Returns the last element of an array as an Optional. * * @example * * ```ts * const queue = ['first', 'second']; * * const emptyQueue: string[] = []; * * const lastValue = Arr.last(queue); * * const none = Arr.last(emptyQueue); * * assert.deepStrictEqual(lastValue, Optional.some('second')); * * assert.deepStrictEqual(none, Optional.none); * ``` */ const last = (array) => // eslint-disable-next-line total-functions/no-unsafe-type-assertion (array.length === 0 ? none : some(array.at(-1))); /** * Alias for `head`. * * @see {@link head} */ const first = head; export { at, first, head, last }; //# sourceMappingURL=array-utils-element-access.mjs.map