Skip to content

Instantly share code, notes, and snippets.

@friendlyanon
Last active March 18, 2020 19:26
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 friendlyanon/69865222ec7d445355dd16734589622a to your computer and use it in GitHub Desktop.
Save friendlyanon/69865222ec7d445355dd16734589622a to your computer and use it in GitHub Desktop.
export const IndexableMap = class extends Map {
constructor(iterable) {
super();
this._values = [];
if (iterable != null) {
for (const [key, value] of iterable) {
this.set(key, value);
}
}
}
set(key, value) {
this.delete(key);
return super.set(key, this._values.push(value) - 1);
}
get(key) {
const index = super.get(key);
if (index != null) {
return this._values[index];
}
}
delete(key) {
const index = super.get(key);
if (index == null) {
return false;
}
this._values.splice(index, 1);
const keyIt = this.keys();
for (;;) {
const step = keyIt.next();
if (step.done || step.value === key) {
break;
}
}
for (const k of keyIt) {
super.set(k, super.get(k) - 1);
}
return super.delete(key);
}
clear() {
this._values = [];
return super.clear();
}
forEach(callback, thisArg) {
for (const [key, value] of this) {
callback.call(thisArg, value, key, this);
}
}
*values() {
yield* this._values;
}
at(index) {
return this._values[index];
}
};
function* entries() {
const keyIt = this.keys();
for (const value of this.values()) {
yield [keyIt.next().value, value];
}
}
const descriptor = {
value: entries,
writable: true,
configurable: true,
};
Object.defineProperties(IndexableMap.prototype, {
entries: descriptor,
[Symbol.iterator]: descriptor,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment