Skip to content

Instantly share code, notes, and snippets.

@caub
Created April 22, 2018 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caub/9a2928eebb3a73501374ef8889f22968 to your computer and use it in GitHub Desktop.
Save caub/9a2928eebb3a73501374ef8889f22968 to your computer and use it in GitHub Desktop.
export default class BetterMap {
constructor(data) {
this.m = new Map(Array.isArray(data) || data instanceof Map ? data : Object.entries(data));
}
set(k, v) { // return BetterMap
this.m.set(k, v);
return new SortableMap(this.m);
}
delete(k) { // return BetterMap
this.m.delete(k, v);
return new SortableMap(this.m);
}
get(k) {
return this.m.get(k);
}
forEach(fn) {
this.m.forEach(fn);
}
filter(fn) {
const a = [...this.m].filter(entry => fn(entry[1]));
return new SortableMap(a);
}
map(fn) { // return Array
return Array.from(this.m.values(), fn);
}
sort(fn) { // return BetterMap
const a = [...this.m].sort((x, y) => fn(x[1], y[1])); // sort with values
return new SortableMap(a);
}
reverse() { // return BetterMap
return new SortableMap([...this.m].reverse());
}
every(fn) {
return [...this.m.values()].every(fn);
}
some(fn) {
return [...this.m.values()].some(fn);
}
get size() {
return this.m.size;
}
values() {
return this.m.values();
}
keys() {
return this.m.keys();
}
toJSON() {
return [...this.m.values()];
}
*[Symbol.iterator]() {
yield* this.m;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment