@monstermann/fn
Version:
A utility library for TypeScript.
40 lines (38 loc) • 1.13 kB
JavaScript
import { FnError } from "../function/FnError.js";
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/mapAtOrThrow.ts
/**
* `mapAtOrThrow(array, index, mapper)`
*
* Applies the `mapper` function to the element at the specified `index` in `array`, returning a new array with the mapped element, or throws an error if the index is out of bounds.
*
* ```ts
* mapAtOrThrow([1, 2, 3, 4], 1, (x) => x * 10); // [1, 20, 3, 4]
* ```
*
* ```ts
* pipe(
* [1, 2, 3, 4],
* mapAtOrThrow(1, (x) => x * 10),
* ); // [1, 20, 3, 4]
* ```
*/
const mapAtOrThrow = dfdlT((target, idx, map) => {
const offset = resolveOffset(target, idx);
if (offset < 0) throw new FnError("Array.mapAtOrThrow: Index is out of range.", [
target,
idx,
map
]);
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 { mapAtOrThrow };