All files / iterable/src first.ts

100% Statements 5/5
100% Branches 0/0
100% Functions 2/2
100% Lines 5/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 371x 1x                                                         4x     1x 4x    
import { alwaysTrue } from "@benneq/predicate";
import { find } from "./find";
 
/**
 * Get the first element of an {@link Iterable}, or an optional default value
 * if the {@link Iterable} is empty.
 *
 * Returns `undefined` if the {@link Iterable} is empty and no `defaultValue`
 * was provided.
 *
 * @example
 * Get the first element
 * ```ts
 * const result = first()([1,2,3]);
 * console.log(result); // 1
 * ```
 *
 * @example
 * Get the first element or the `defaultValue`
 * ```ts
 * const result = first(1)([]);
 * console.log(result); // 1
 * ```
 *
 * @see {@link filter} and {@link find} for similar operations.
 *
 * @typeParam T - the {@link Iterable} value type
 * @param defaultValue - the default value
 * @returns the first element of the {@link Iterable}, or the defaultValue
 */
export const first: {
  <T>(): (iterable: Iterable<T>) => T | undefined;
  <T>(defaultValue: T): (iterable: Iterable<T>) => T;
} = <T>(defaultValue?: T): ((iterable: Iterable<T>) => T | undefined) => {
  return find(alwaysTrue, defaultValue);
};