@monstermann/fn
Version:
A utility library for TypeScript.
36 lines (34 loc) • 1.05 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/replaceOrThrow.ts
/**
* `replaceOrThrow(target, value, replacement)`
*
* Replaces the first occurrence of `value` in `target` with `replacement`. If `value` is not found, throws an error.
*
* ```ts
* replaceOrThrow([1, 2, 3, 2], 2, 9); // [1, 9, 3, 2]
* replaceOrThrow([1, 2, 3], 4, 9); // throws FnError
* ```
*
* ```ts
* pipe([1, 2, 3, 2], replaceOrThrow(2, 9)); // [1, 9, 3, 2]
* pipe([1, 2, 3], replaceOrThrow(4, 9)); // throws FnError
* ```
*/
const replaceOrThrow = dfdlT((target, value, replacement) => {
if (is(value, replacement)) return target;
const idx = target.indexOf(value);
if (idx === -1) throw new FnError("Array.replaceOrThrow: Value not found.", [
target,
value,
replacement
]);
const result = cloneArray(target);
result.splice(idx, 1, replacement);
return result;
}, 3);
//#endregion
export { replaceOrThrow };