All files / iterable/src map.ts

100% Statements 5/5
100% Branches 0/0
100% Functions 3/3
100% Lines 4/4

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                                        1x 1x 1x 3x      
import { Mapper } from "@benneq/function";
 
/**
 * Maps every element of an {@link Iterable} using a {@link Mapper} function.
 *
 * @example
 * Square all numbers
 * ```ts
 * const square = map(x => x * x);
 * const result = square([1, 2, 3]);
 * console.log(result); // [1, 4, 9]
 * ```
 *
 * @see {@link flatMap}, {@link groupBy}, and {@link reduce} for similar operations.
 *
 * @typeParam T - the source {@link Iterable} value type
 * @typeParam R - the target {@link Iterable} value type
 * @param mapper
 * @returns an {@link Iterable} that emits all mapped elements
 */
export const map = <T, R>(mapper: Mapper<T, R>) =>
  function* (iterable: Iterable<T>): IterableIterator<R> {
    for (const value of iterable) {
      yield mapper(value);
    }
  };