Skip to content

Instantly share code, notes, and snippets.

@jorendorff
Last active December 17, 2015 17:19
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 jorendorff/5645591 to your computer and use it in GitHub Desktop.
Save jorendorff/5645591 to your computer and use it in GitHub Desktop.
Trying to argue that Tab's use case in http://esdiscuss.org/topic/overridingmapetcwithgetsethooks is not as big a deal for JS programmers as it is for spec authors.
class Maplike {
// Subclasses define @@iterator(), set(), and delete().
// Typically a subclass will also define get(), has(), and size, for performance.
get size() {
let n = 0;
for (let _ of this)
n++;
return n;
}
get(key) {
for (let [k, v] of this)
if (sameValue(k, key))
return v;
}
has(key) {
for (let [k, v] of this)
if (sameValue(k, key))
return true;
return false;
}
*entries() {
for (let pair of this)
yield pair;
}
*keys() {
for (let [k, _] of this)
yield k;
}
*values() {
for (let [_, v] of this)
yield v;
}
clear() {
for (let k of [...this.keys()])
this.delete(k);
}
forEach(callbackFn, thisArg) {
for (let [k, v] of this)
callbackFn.call(thisArg, v, k, this);
}
}
class MapWithKeyCoercion {
constructor(coerceKeyFn, data = undefined) {
this._map = new Map;
this._key = coerceKeyFn;
if (data !== undefined) {
for (let [k, v] of data)
this.set(k, v);
}
}
get size() { return this._map.size; }
get(key) { return this._map.get(this._key(key)); }
has(key) { return this._map.has(this._key(key)); }
set(key, value) { return this._map.set(this._key(key), value); }
entries() { return this._map.entries(); }
keys() { return this._map.keys(); }
values() { return this._map.values(); }
clear() { return this._map.clear(); }
forEach(callbackFn, thisArg) { return this._map.forEach(callbackFn, thisArg); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment