All files findIndex.ts

96% Statements 24/25
75% Branches 6/8
100% Functions 9/9
95.45% Lines 21/22

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 78 798x   8x 8x                                             8x 4x     8x       3x       7x     16x     2x 2x 4x 4x 2x           2x 2x             8x               8x 1x     8x   8x    
import { purry } from './purry';
import { Pred, PredIndexedOptional, PredIndexed } from './_types';
import { _toLazyIndexed } from './_toLazyIndexed';
import { _toSingle } from './_toSingle';
 
/**
 * Returns the index of the first element in the array where predicate is true, and -1 otherwise.
 * @param items - the array
 * @param fn - the predicate
 * @signature
 *    P.findIndex(items, fn)
 * @signature
 *    P.findIndex(fn)(items)
 * @example
 *    P.findIndex([1, 3, 4, 6], n => n % 2 === 0) // => 2
 *    P.pipe(
 *      [1, 3, 4, 6],
 *      P.findIndex(n => n % 2 === 0)
 *    ) // => 4
 * @category Array, Pipe
 */
export function findIndex<T>(array: readonly T[], fn: Pred<T, boolean>): number;
export function findIndex<T>(
  fn: Pred<T, boolean>
): (array: readonly T[]) => number;
 
export function findIndex() {
  return purry(_findIndex(false), arguments, findIndex.lazy);
}
 
const _findIndex = (indexed: boolean) => <T>(
  array: T[],
  fn: PredIndexedOptional<T, boolean>
) => {
  Iif (indexed) {
    return array.findIndex(fn);
  }
 
  return array.findIndex(x => fn(x));
};
 
const _lazy = (indexed: boolean) => <T>(
  fn: PredIndexedOptional<T, boolean>
) => {
  let i = 0;
  return (value: T, index?: number, array?: T[]) => {
    const valid = indexed ? fn(value, index, array) : fn(value);
    if (valid) {
      return {
        done: true,
        hasNext: true,
        next: i,
      };
    }
    i++;
    return {
      done: false,
      hasNext: false,
    };
  };
};
 
export namespace findIndex {
  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(_findIndex(true), arguments, findIndex.lazyIndexed);
  }
 
  export const lazy = _toSingle(_lazy(false));
 
  export const lazyIndexed = _toSingle(_toLazyIndexed(_lazy(true)));
}