All files / iterable/src filter.ts

100% Statements 6/6
100% Branches 1/1
100% Functions 3/3
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                                          1x 1x 1x 4x 2x        
import { Predicate } from "@benneq/predicate";
 
/**
 * Only emits elements from an {@link Iterable} that match the given
 * {@link Predicate}.
 *
 * @example
 * Filter even numbers
 * ```ts
 * const filterEven = filter(isEven);
 * const iterable = [1,2,3,4];
 * const filteredIterable = filterEven(iterable);
 * console.log(filteredIterable); // [2,4]
 * ```
 *
 * @see {@link distinct}, {@link findFirst} and {@link first} for similar operations.
 *
 * @typeParam T - the {@link Iterable} value type
 * @param predicate - the {@link Predicate} to match
 * @returns an {@link Iterable} that only emits values for which the {@link Predicate} returns `true`
 */
export const filter = <T>(predicate: Predicate<[T]>) =>
  function* (iterable: Iterable<T>): IterableIterator<T> {
    for (const value of iterable) {
      if (predicate(value)) {
        yield value;
      }
    }
  };