@monstermann/fn
Version:
A utility library for TypeScript.
35 lines (33 loc) • 953 B
JavaScript
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/mapAtOr.ts
/**
* `mapAtOr(array, index, mapper, fallback)`
*
* Applies the `mapper` function to the element at the specified `index` in `array`, returning a new array with the mapped element, or `fallback` if the index is out of bounds.
*
* ```ts
* mapAtOr([1, 2, 3], 10, (x) => x * 10, []); // []
* ```
*
* ```ts
* pipe(
* [1, 2, 3],
* mapAtOr(10, (x) => x * 10, []),
* ); // []
* ```
*/
const mapAtOr = dfdlT((target, idx, map, or) => {
const offset = resolveOffset(target, idx);
if (offset < 0) return or;
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 { mapAtOr };