All files / iterable/src takeWhile.ts

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

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                                        5x 5x 5x 14x 2x   12x      
import { Predicate } from "@benneq/predicate";
 
/**
 * Emits all elements of an {@link Iterable} while a {@link Predicate} matches.
 *
 * Terminates the {@link Iterable} when the {@link Predicate} returns `false`.
 *
 * @example
 * ```ts
 * const takeWhileLessThan3 = takeWhile(x => x < 3);
 * const iterable = takeWhileLessThan3([1,2,3,4]);
 * console.log(iterable); // [1,2]
 * ```
 *
 * @see {@link dropWhile}, {@link limit} and {@link skip} for similar operations.
 *
 * @typeParam T - the {@link Iterable} value type
 * @param predicate - the {@link Predicate} to match
 * @returns an {@link Iterable} that emits values until the {@link Predicate} returns `false`
 */
export const takeWhile = <T>(predicate: Predicate<[T]>) =>
  function* (iterable: Iterable<T>): IterableIterator<T> {
    for (const value of iterable) {
      if (!predicate(value)) {
        return;
      }
      yield value;
    }
  };