lib0
Version:
> Monorepo of isomorphic utility functions
134 lines (124 loc) • 2.47 kB
JavaScript
/**
* Utility module to work with key-value stores.
*
* @module map
*/
/**
* Creates a new Map instance.
*
* @function
* @return {Map<any, any>}
*
* @function
*/
const create = () => new Map();
/**
* Copy a Map object into a fresh Map object.
*
* @function
* @template X,Y
* @param {Map<X,Y>} m
* @return {Map<X,Y>}
*/
const copy = m => {
const r = create();
m.forEach((v, k) => { r.set(k, v); });
return r
};
/**
* Get map property. Create T if property is undefined and set T on map.
*
* ```js
* const listeners = map.setIfUndefined(events, 'eventName', set.create)
* listeners.add(listener)
* ```
*
* @function
* @template V,K
* @template {Map<K,V>} MAP
* @param {MAP} map
* @param {K} key
* @param {function():V} createT
* @return {V}
*/
const setIfUndefined = (map, key, createT) => {
let set = map.get(key);
if (set === undefined) {
map.set(key, set = createT());
}
return set
};
/**
* Creates an Array and populates it with the content of all key-value pairs using the `f(value, key)` function.
*
* @function
* @template K
* @template V
* @template R
* @param {Map<K,V>} m
* @param {function(V,K):R} f
* @return {Array<R>}
*/
const map = (m, f) => {
const res = [];
for (const [key, value] of m) {
res.push(f(value, key));
}
return res
};
/**
* Tests whether any key-value pairs pass the test implemented by `f(value, key)`.
*
* @todo should rename to some - similarly to Array.some
*
* @function
* @template K
* @template V
* @param {Map<K,V>} m
* @param {function(V,K):boolean} f
* @return {boolean}
*/
const any = (m, f) => {
for (const [key, value] of m) {
if (f(value, key)) {
return true
}
}
return false
};
/**
* Tests whether all key-value pairs pass the test implemented by `f(value, key)`.
*
* @function
* @template K
* @template V
* @param {Map<K,V>} m
* @param {function(V,K):boolean} f
* @return {boolean}
*/
const all = (m, f) => {
for (const [key, value] of m) {
if (!f(value, key)) {
return false
}
}
return true
};
var map$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
create: create,
copy: copy,
setIfUndefined: setIfUndefined,
map: map,
any: any,
all: all
});
exports.all = all;
exports.any = any;
exports.copy = copy;
exports.create = create;
exports.map = map;
exports.map$1 = map$1;
exports.setIfUndefined = setIfUndefined;
//# sourceMappingURL=map-9a5915e4.cjs.map
;