@monstermann/fn
Version:
A utility library for TypeScript.
38 lines (36 loc) • 885 B
JavaScript
import { dfdlT } from "@monstermann/dfdl";
//#region src/set/mapEach.ts
/**
* `mapEach(target, fn)`
*
* Transforms each value in the `target` set using the `fn` function and returns a new set with the transformed values.
*
* ```ts
* mapEach(new Set([1, 2, 3]), (x) => x * 2); // Set([2, 4, 6])
* mapEach(new Set(["a", "b"]), (x) => x.toUpperCase()); // Set(['A', 'B'])
* ```
*
* ```ts
* pipe(
* new Set([1, 2, 3]),
* mapEach((x) => x * 2),
* ); // Set([2, 4, 6])
*
* pipe(
* new Set(["a", "b"]),
* mapEach((x) => x.toUpperCase()),
* ); // Set(['A', 'B'])
* ```
*/
const mapEach = dfdlT((target, fn) => {
let hasChanges = false;
const result = /* @__PURE__ */ new Set();
for (const prev of target) {
const next = fn(prev, target);
hasChanges ||= prev !== next;
result.add(next);
}
return hasChanges ? result : target;
}, 2);
//#endregion
export { mapEach };