UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

43 lines (41 loc) 891 B
import { is } from "../function/is.js"; import { dfdlT } from "@monstermann/dfdl"; import { cloneMap } from "@monstermann/remmi"; //#region src/map/mapEach.ts /** * `mapEach(map, fn)` * * Maps each value in `map` using `fn`, returning a new map with the transformed values. * * ```ts * mapEach( * new Map([ * ["a", 1], * ["b", 2], * ]), * (value, key) => value * 2, * ); // Map(2) { "a" => 2, "b" => 4 } * ``` * * ```ts * pipe( * new Map([ * ["a", 1], * ["b", 2], * ]), * mapEach((value, key) => value * 2), * ); // Map(2) { "a" => 2, "b" => 4 } * ``` */ const mapEach = dfdlT((target, fn) => { let result; for (const [k, prev] of target) { const next = fn(prev, k, target); if (is(prev, next)) continue; result ??= cloneMap(target); result.set(k, next); } return result ?? target; }, 2); //#endregion export { mapEach };