jsadvent/lib/Maps.js
2020-12-10 02:33:00 -06:00

39 lines
824 B
JavaScript

module.exports = class Maps {
static and(...maps) {
if (maps.length === 0) {
return [];
}
const outputs = [];
for (const i of maps) {
outputs.push(new Map());
}
const [map1, ...rest] = maps;
for (const k of map1.keys()) {
if (rest.every((map) => map.has(k))) {
for (let i = 0; i < maps.length; i++) {
outputs[i].set(k, maps[i].get(k));
}
}
}
return outputs;
}
static combineBy(combineFn, ...maps) {
const result = new Map();
for (const map of maps) {
for (const [k, v] of map.entries()) {
result.set(k, result.has(k) ? combineFn(k, result.get(k), v) : v);
}
}
return result;
}
static add(...maps) {
return Maps.combineBy((k, v1, v2) => {
return v1 + v2;
}, ...maps);
}
};