Last active
December 17, 2015 17:19
-
-
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.
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
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); | |
} | |
} |
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
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