All files find.ts

100% Statements 21/21
83.33% Branches 5/6
100% Functions 9/9
100% Lines 18/18

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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 7811x   11x 11x                                                           11x 5x     11x       2x 1x     2x     22x     5x 17x 17x               11x               11x 2x     11x   11x    
import { purry } from './purry';
import { Pred, PredIndexedOptional, PredIndexed } from './_types';
import { _toLazyIndexed } from './_toLazyIndexed';
import { _toSingle } from './_toSingle';
 
/**
 * Returns the value of the first element in the array where predicate is true, and undefined otherwise.
 * @param items the array
 * @param fn the predicate
 * @signature
 *    P.find(items, fn)
 * @signature
 *    P.find(fn)(items)
 * @example
 *    P.find([1, 3, 4, 6], n => n % 2 === 0) // => 4
 *    P.pipe(
 *      [1, 3, 4, 6],
 *      P.find(n => n % 2 === 0)
 *    ) // => 4
 *    P.pipe(
 *      [1, 3, 4, 6],
 *      P.find.indexed((n, i) => n % 2 === 0)
 *    ) // => 4
 * @category Array, Pipe
 */
export function find<T>(
  array: readonly T[],
  fn: Pred<T, boolean>
): T | undefined;
export function find<T = never>(
  fn: Pred<T, boolean>
): (array: readonly T[]) => T | undefined;
 
export function find() {
  return purry(_find(false), arguments, find.lazy);
}
 
const _find = (indexed: boolean) => <T>(
  array: T[],
  fn: PredIndexedOptional<T, boolean>
) => {
  if (indexed) {
    return array.find(fn);
  }
 
  return array.find(x => fn(x));
};
 
const _lazy = (indexed: boolean) => <T>(
  fn: PredIndexedOptional<T, boolean>
) => {
  return (value: T, index?: number, array?: T[]) => {
    const valid = indexed ? fn(value, index, array) : fn(value);
    return {
      done: valid,
      hasNext: valid,
      next: value,
    };
  };
};
 
export namespace find {
  export function indexed<T>(
    array: readonly T[],
    fn: PredIndexed<T, boolean>
  ): T | undefined;
  export function indexed<T>(
    fn: PredIndexed<T, boolean>
  ): (array: readonly T[]) => T | undefined;
  export function indexed() {
    return purry(_find(true), arguments, find.lazyIndexed);
  }
 
  export const lazy = _toSingle(_lazy(false));
 
  export const lazyIndexed = _toSingle(_toLazyIndexed(_lazy(true)));
}