UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

44 lines (42 loc) 1.13 kB
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/mapAtOrElse.ts /** * `mapAtOrElse(array, index, mapper, callback)` * * Applies the `mapper` function to the element at the specified `index` in `array`, returning a new array with the mapped element, or the result of calling `callback` with the array if the index is out of bounds. * * ```ts * mapAtOrElse( * [1, 2, 3], * 10, * (x) => x * 10, * (arr) => arr.length, * ); // 3 * ``` * * ```ts * pipe( * [1, 2, 3], * mapAtOrElse( * 10, * (x) => x * 10, * (arr) => arr.length, * ), * ); // 3 * ``` */ const mapAtOrElse = dfdlT((target, idx, map, orElse) => { const offset = resolveOffset(target, idx); if (offset < 0) return orElse(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; }, 4); //#endregion export { mapAtOrElse };