All files filter.ts

100% Statements 20/20
87.5% Branches 7/8
100% Functions 8/8
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 78 79 80 81 82 83 84 854x 4x   4x                                                                     4x 7x     9x       2x             8x     9x 28x 28x 16x           12x             4x         4x 2x     4x 4x    
import { purry } from './purry';
import { _reduceLazy, LazyResult } from './_reduceLazy';
import { Pred, PredIndexedOptional, PredIndexed } from './_types';
import { _toLazyIndexed } from './_toLazyIndexed';
 
/**
 * Filter the elements of an array that meet the condition specified in a callback function.
 * @param array The array to filter.
 * @param fn the callback function.
 * @signature
 *    R.filter(array, fn)
 *    R.filter.indexed(array, fn)
 * @example
 *    R.filter([1, 2, 3], x => x % 2 === 1) // => [1, 3]
 *    R.filter.indexed([1, 2, 3], (x, i, array) => x % 2 === 1) // => [1, 3]
 * @data_first
 * @indexed
 * @pipeable
 * @category Array
 */
export function filter<T>(array: T[], fn: Pred<T, boolean>): T[];
 
/**
 * Filter the elements of an array that meet the condition specified in a callback function.
 * @param fn the callback function.
 * @signature
 *    R.filter(fn)(array)
 *    R.filter.indexed(fn)(array)
 * @example
 *    R.pipe([1, 2, 3], R.filter(x => x % 2 === 1)) // => [1, 3]
 *    R.pipe([1, 2, 3], R.filter.indexed((x, i) => x % 2 === 1)) // => [1, 3]
 * @data_last
 * @indexed
 * @pipeable
 * @category Array
 */
export function filter<T>(fn: Pred<T, boolean>): (array: T[]) => T[];
 
export function filter() {
  return purry(_filter(false), arguments, filter.lazy);
}
 
const _filter = (indexed: boolean) => <T>(
  array: T[],
  fn: PredIndexedOptional<T, boolean>
) => {
  return _reduceLazy(
    array,
    indexed ? filter.lazyIndexed(fn) : filter.lazy(fn),
    indexed
  );
};
 
const _lazy = (indexed: boolean) => <T>(
  fn: PredIndexedOptional<T, boolean>
) => {
  return (value: T, index?: number, array?: T[]): LazyResult<T> => {
    const valid = indexed ? fn(value, index, array) : fn(value);
    if (!!valid === true) {
      return {
        done: false,
        hasNext: true,
        next: value,
      };
    }
    return {
      done: false,
      hasNext: false,
    };
  };
};
 
export namespace filter {
  export function indexed<T, K>(array: T[], fn: PredIndexed<T, boolean>): K[];
  export function indexed<T, K>(
    fn: PredIndexed<T, boolean>
  ): (array: T[]) => K[];
  export function indexed() {
    return purry(_filter(true), arguments, filter.lazyIndexed);
  }
 
  export const lazy = _lazy(false);
  export const lazyIndexed = _toLazyIndexed(_lazy(true));
}