@alexaegis/advent-of-code-lib
Version:
Advent of Code Library
48 lines (47 loc) • 1.21 kB
JavaScript
const mapGetOrSet = (map, key, initialize) => {
const value = map.get(key);
if (value) {
return value;
} else {
const newValue = initialize(key);
map.set(key, newValue);
return newValue;
}
};
Map.prototype.print = function() {
console.info(this.toString());
};
Map.prototype.toString = function() {
return JSON.stringify(this.intoDictionary());
};
Map.prototype.keyArray = function() {
return [...this.keys()];
};
Map.prototype.valueArray = function() {
return [...this.values()];
};
Map.prototype.entryArray = function() {
return [...this.entries()];
};
Map.prototype.intoDictionary = function() {
return Object.fromEntries(this.entries());
};
Map.prototype.copy = function() {
return new Map(this.entries());
};
Map.prototype.update = function(key, change) {
this.set(key, change(this.get(key)));
return this;
};
Map.prototype.findKey = function(value) {
return [...this.entries()].find((e) => e[1] === value);
};
Map.prototype.getOrAdd = function(key, initialize) {
return mapGetOrSet(this, key, initialize);
};
Map.prototype.isTheSameAs = function(other) {
return [...this.keys()].every((key) => this.get(key) === other.get(key));
};
export {
mapGetOrSet
};