All files / iterable/src find.ts

100% Statements 7/7
100% Branches 1/1
100% Functions 3/3
100% Lines 7/7

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 37 38 39 40 41 42 43 44 45 46                                                                11x       2x 11x 11x 6x 5x     6x    
import { Predicate } from "@benneq/predicate";
 
/**
 * Find the first matching element of an {@link Iterable}, or a 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 matching element
 * ```ts
 * const findFirstEven = findFirst(isEven);
 * const result = findFirstEven([1,2,3]);
 * console.log(result); // 2
 * ```
 *
 * @example
 * Get the first matching element or the `defaultValue`
 * ```ts
 * const findFirstEven = findFirst(isEven, 2);
 * const result = findFirstEven([1]);
 * console.log(result); // 2
 * ```
 *
 * @see {@link filter} and {@link first} for similar operations.
 *
 * @typeParam T - the {@link Iterable} value type
 * @param predicate - the {@link Predicate} to match
 * @param defaultValue
 * @returns the first matching element of the {@link Iterable}, or the given `defaultValue`
 */
export const find: {
  <T>(predicate: Predicate<[T]>): (iterable: Iterable<T>) => T | undefined;
  <T>(predicate: Predicate<[T]>, defaultValue: T): (iterable: Iterable<T>) => T;
} =
  <T>(predicate: Predicate<[T]>, defaultValue?: T) =>
  (iterable: Iterable<T>): T | undefined => {
    for (const value of iterable) {
      if (predicate(value)) {
        return value;
      }
    }
    return defaultValue;
  };