@monstermann/fn
Version:
A utility library for TypeScript.
36 lines (34 loc) • 1.09 kB
JavaScript
import { FnError } from "../function/FnError.js";
import { is } from "../function/is.js";
import { dfdlT } from "@monstermann/dfdl";
import { cloneArray } from "@monstermann/remmi";
//#region src/array/replaceLastOrThrow.ts
/**
* `replaceLastOrThrow(target, value, replacement)`
*
* Replaces the last occurrence of `value` in `target` with `replacement`. If `value` is not found, throws an error.
*
* ```ts
* replaceLastOrThrow([1, 2, 3, 2], 2, 9); // [1, 2, 3, 9]
* replaceLastOrThrow([1, 2, 3], 4, 9); // throws FnError
* ```
*
* ```ts
* pipe([1, 2, 3, 2], replaceLastOrThrow(2, 9)); // [1, 2, 3, 9]
* pipe([1, 2, 3], replaceLastOrThrow(4, 9)); // throws FnError
* ```
*/
const replaceLastOrThrow = dfdlT((target, value, replacement) => {
if (is(value, replacement)) return target;
const idx = target.lastIndexOf(value);
if (idx === -1) throw new FnError("Array.replaceLastOrThrow: Value not found", [
target,
value,
replacement
]);
const result = cloneArray(target);
result.splice(idx, 1, replacement);
return result;
}, 3);
//#endregion
export { replaceLastOrThrow };