JSFiddle - React, Tailwind, and code Playground
by brigand
JavaScript
class Entry {
constructor(map, key) {
this.map = map;
this.key = key;
}
get() {
return this.map.get(this.key);
}
set(value) {
this.map.set(this.key, value)
}
has() {
return this.map.has(this.key);
}
transform(f) {
this.set(f(this.get));
}
orDefault() {
if (this.has()) {
return this.get();
} else {
const value = this.map.defaultValue();
this.set(value);
return value;
}
}
}
class Map2 extends Map {
defaultValue() {
return null;
}
entry(key) {
return new Entry(this, key);
}
}
class MapMap extends Map2 {
defaultValue() {
return new Map2();
}
}
const map = new MapMap();
map.entry('first').orDefault().entry('foo').set(7);
map.entry('first').orDefault().entry('bar').set(13);
map.entry('second').orDefault().entry('baz').set(23);
for (const [k1, v1] of map) {
for (const [k2, v2] of v1) {
console.log(k1, k2, v2);
}
}