jsadvent/lib/_pollute/map.js
2020-12-12 00:59:44 -06:00

64 lines
1.3 KiB
JavaScript

const Glib = require('../glib');
Object.defineProperty(Map.prototype, 'glibEntries', {
enumerable: false,
configurable: false,
get() {
return new Glib(this.entries());
},
});
Object.defineProperty(Map.prototype, 'glibKeys', {
enumerable: false,
configurable: false,
get() {
return new Glib(this.keys());
},
});
Object.defineProperty(Map.prototype, 'glibValues', {
enumerable: false,
configurable: false,
get() {
return new Glib(this.values());
},
});
Map.prototype.update = function update(key, updateFn) {
this.set(key, updateFn(this.get(key), key));
return this;
};
const _getPath = (map, path) => {
for (const component of path) {
if (!map.has(component)) {
return undefined;
}
map = map.get(component);
}
return map;
};
Map.prototype.hasPath = function hasPath(path) {
path = Array.from(path);
const map = _getPath(this, path.slice(0, -1));
if (!map) {
return false;
}
return map.has(path[path.length - 1]);
};
Map.prototype.getPath = function getPath(path) {
return _getPath(this, path);
};
Map.prototype.setPath = function setPath(path, value) {
path = Array.from(path);
let map = this;
for (const component of path.slice(0, -1)) {
map.set(component, (map = map.get(component) || new Map()));
}
map.set(path[path.length - 1], value);
return this;
};