UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

35 lines (33 loc) 904 B
import { is } from "../function/is.js"; import { resolveOffset } from "./internals/offset.js"; import { dfdlT } from "@monstermann/dfdl"; import { cloneArray } from "@monstermann/remmi"; //#region src/array/mapAt.ts /** * `mapAt(array, index, mapper)` * * Applies the `mapper` function to the element at the specified `index` in `array`, returning a new array with the mapped element. * * ```ts * mapAt([1, 2, 3, 4], 1, (x) => x * 10); // [1, 20, 3, 4] * ``` * * ```ts * pipe( * [1, 2, 3, 4], * mapAt(1, (x) => x * 10), * ); // [1, 20, 3, 4] * ``` */ const mapAt = dfdlT((target, idx, map) => { const offset = resolveOffset(target, idx); if (offset < 0) return target; const prev = target[offset]; const next = map(prev, offset, target); if (is(prev, next)) return target; target = cloneArray(target); target.splice(offset, 1, next); return target; }, 3); //#endregion export { mapAt };