@monstermann/fn
Version:
A utility library for TypeScript.
29 lines (27 loc) • 841 B
JavaScript
import { FnError } from "../function/FnError.js";
import { dfdlT } from "@monstermann/dfdl";
import { cloneSet } from "@monstermann/remmi";
//#region src/set/addOrThrow.ts
/**
* `addOrThrow(target, value)`
*
* Adds a `value` to the `target` set and returns a new set. If the value already exists in the set, throws an error.
*
* ```ts
* addOrThrow(new Set([1, 2]), 3); // Set([1, 2, 3])
* addOrThrow(new Set([1, 2]), 2); // throws FnError
* ```
*
* ```ts
* pipe(new Set([1, 2]), addOrThrow(3)); // Set([1, 2, 3])
* pipe(new Set([1, 2]), addOrThrow(2)); // throws FnError
* ```
*/
const addOrThrow = dfdlT((target, value) => {
if (target.has(value)) throw new FnError("Set.addOrThrow: Value already exists.", [target, value]);
const result = cloneSet(target);
result.add(value);
return result;
}, 2);
//#endregion
export { addOrThrow };