shelving
Version:
Toolkit for using data in JavaScript.
55 lines (54 loc) • 2.13 kB
JavaScript
import { RequiredError } from "../error/RequiredError.js";
import { isIterable, limitItems } from "./iterate.js";
/** Class for a `Map` that cannot be changed (so you can extend `Map` while implementing `ImmutableMap`). */
export const ImmutableMap = Map;
/** Is an unknown value a map? */
export function isMap(value) {
return value instanceof Map;
}
/** Assert that a value is a `Map` instance. */
export function assertMap(value, caller = assertMap) {
if (!isMap(value))
throw new RequiredError("Must be map", { received: value, caller });
}
export function getMap(input) {
return isMap(input) ? input : new Map(isIterable(input) ? input : Object.entries(input));
}
/** Apply a limit to a map. */
export function limitMap(map, limit) {
return limit > map.size ? map : new Map(limitItems(map, limit));
}
/** Is an unknown value a key for an item in a map? */
export function isMapItem(map, key) {
return map.has(key);
}
/** Assert that an unknown value is a key for an item in a map. */
export function assertMapItem(map, key, caller = assertMapItem) {
if (!isMapItem(map, key))
throw new RequiredError("Key must exist in map", { key, map, caller });
}
/** Function that lets new items in a map be created and updated by calling a `reduce()` callback that receives the existing value. */
export function setMapItem(map, key, value) {
map.set(key, value);
return value;
}
/** Add multiple items to a set (by reference). */
export function setMapItems(map, items) {
for (const [k, v] of items)
map.set(k, v);
}
/** Remove multiple items from a set (by reference). */
export function removeMapItems(map, ...keys) {
for (const key of keys)
map.delete(key);
}
/** Get an item in a map, or `undefined` if it doesn't exist. */
export function getMapItem(map, key) {
return map.get(key);
}
/** Get an item in a map, or throw `RequiredError` if it doesn't exist. */
export function requireMapItem(map, key, caller = requireMapItem) {
if (!map.has(key))
throw new RequiredError("Key must exist in map", { key, map, caller });
return map.get(key);
}