All files / array/src mapTuple.ts

100% Statements 5/5
100% Branches 0/0
100% Functions 4/4
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 28 29 30 31 32 33                                                2x 1x       2x 4x    
import { Mapper } from "@benneq/function";
 
/**
 * Maps each element of a tuple individually using its own {@link Mapper}.
 *
 * @example
 * ```ts
 * const tuple = [1, "abc"];
 *
 * const mapper = mapTuple(
 *   (num) => num > 0,
 *   (str) => str.length,
 * );
 *
 * const result = mapper(tuple);
 *
 * console.log(result); // [true, 3]
 * ```
 *
 * @paramType TArgs - the type of the input tuple
 * @paramType RArgs - the type of the mapped output tuple
 * @param mappers - the {@link Mapper}s to use
 * @returns the mapped tuple
 */
export const mapTuple =
  <
    TArgs extends unknown[],
    RArgs extends { [index in keyof TArgs]: unknown }
  >(mappers: { [index in keyof TArgs]: Mapper<TArgs[index], RArgs[index]> }) =>
  (tuple: TArgs): RArgs => {
    return mappers.map((mapper, index) => mapper(tuple[index])) as RArgs;
  };