All files / iterable/src tap.ts

100% Statements 6/6
100% Branches 0/0
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                                  1x     1x 1x 2x 2x        
import { Callback } from "@benneq/function";
 
/**
 * Calls a {@link Callback} for each element of an {@link Iterable}.
 *
 * @example
 * Print all elements
 * ```ts
 * const printAll = tap(x => console.log(x));
 * printAll([1, 2, 3]); // 1, 2, 3
 * ```
 *
 * @see {@link forEach} and {@link map} for similar operations
 *
 * @typeParam T - the {@link Iterable} value type
 * @param callback - the {@link Callback} to call
 */
export const tap = <T>(
  callback: Callback<[T]>
): ((iterable: Iterable<T>) => IterableIterator<T>) => {
  return function* (iterable) {
    for (const value of iterable) {
      callback(value);
      yield value;
    }
  };
};