Last active
March 18, 2020 19:26
-
-
Save friendlyanon/69865222ec7d445355dd16734589622a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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