@beenotung/tslib
Version:
utils library in Typescript
75 lines (74 loc) • 1.87 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.collectMap = collectMap;
exports.mapToArray = mapToArray;
exports.reduceMap = reduceMap;
exports.mapGetOrThrow = mapGetOrThrow;
exports.mapGetOrSetDefault = mapGetOrSetDefault;
exports.mapGetMap = mapGetMap;
exports.mapGetSet = mapGetSet;
exports.mapGetArray = mapGetArray;
exports.incMap = incMap;
function collectMap(map, mapper) {
const res = new Map();
map.forEach((value, key) => {
const a = mapper(value, key);
const vs = res.get(a);
if (vs) {
vs.push(value);
}
else {
res.set(a, [value]);
}
});
return res;
}
function mapToArray(map, f) {
const res = [];
map.forEach((v, k, m) => res.push(f(v, k, m)));
return res;
}
function reduceMap(map, mapper, initial) {
let acc = initial;
map.forEach((value, key) => {
acc = mapper(acc, value, key);
});
return acc;
}
function mapGetOrThrow(map, key, message = key + ' not found') {
if (map.has(key)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return map.get(key);
}
if (typeof message === 'string') {
throw new Error(message);
}
else {
throw message;
}
}
function mapGetOrSetDefault(map, key, f) {
if (map.has(key)) {
return map.get(key);
}
const res = f();
map.set(key, res);
return res;
}
function mapGetMap(map, key) {
return mapGetOrSetDefault(map, key, () => new Map());
}
function mapGetSet(map, key) {
return mapGetOrSetDefault(map, key, () => new Set());
}
function mapGetArray(map, key) {
return mapGetOrSetDefault(map, key, () => []);
}
function incMap(map, key) {
if (map.has(key)) {
map.set(key, map.get(key) + 1);
}
else {
map.set(key, 1);
}
}