map-fns
Version:
<h1 align="center"> <code>map-fns</code> </h1>
56 lines (55 loc) • 1.58 kB
TypeScript
import { AnyMap, MapOf } from "../types";
declare type DeepMergable<T> = ((item: T) => DeepMergable<T>) | {
[K in keyof T]?: DeepMergable<T[K]> | ((item: T[K]) => DeepMergable<T[K]>);
};
/**
* Creates a new `map` populated with every key in the original `map` where the
* value behind each `k` in `keys` is the value `map[k]` shallowly merged with
* the return value of `fn(map[k])`.
*
* ```tsx
* newMap[k] = { ...map[k], ...fn(map[k]) };
* ```
*
* Example usage:
*
* ```tsx
* const out = modifyInMap(
* { alice: { age: 34, gender: "f" }, bob: { age: 42, gender: "m" } },
* "alice",
* person => ({ age: person.age + 1 }),
* );
* console.log(out.alice); // { age: 35, gender: "f" }
* console.log(out.bob); // { age: 42, gender: "m" }
* ```
*
* The original `map` is not modified.
*
* An error is thrown if any key in `keys` does not exist in the map.
*
* @param map - The map to copy and modify.
* @param keys - The keys to merge within the map.
* @returns A new map with modified values.
*/
export default function mergeInMap<M extends MapOf<AnyMap>, K extends keyof M = keyof M>(map: M, keys: K | K[],
/**
* Expects a partial value of `map[key]`.
*
* Supports returning functions to compute properties like so:
*
* ```tsx
* const map = { key: { count: 1 } };
*
* // "Normal" syntax
* mergeInMap(map, "key", (item) => ({
* count: item.count + 1,
* }));
*
* // Compute function
* mergeInMap(map, "key", () => ({
* count: (count) => count + 1,
* }));
* ```
*/
toMerge: DeepMergable<M[K]>): M;
export {};