Skip to content

Instantly share code, notes, and snippets.

@jorendorff
Last active December 17, 2015 19:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jorendorff/5662673 to your computer and use it in GitHub Desktop.
Save jorendorff/5662673 to your computer and use it in GitHub Desktop.
class Mapping {
// Subclasses define at least @@iterator().
@@iterator() {
throw TypeError("abstract operation")
}
// Mutable subclasses also define set() and delete().
set(key, value) {
throw TypeError("mapping is not mutable");
}
delete(key) {
throw TypeError("mapping is not mutable");
}
// The other methods are defined in terms of the basic operations above.
// But typically a subclass will also define at least 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;
}
clear() {
for (let k of [...this.keys()])
this.delete(k);
}
*entries() {
for (let pair of this)
yield pair;
}
*keys() {
for (let [k, _] of this)
yield k;
}
*values() {
for (let [_, v] of this)
yield v;
}
forEach(callbackFn, thisArg) {
// This would be specified in terms of [[Call]] rather than the .call method.
for (let [k, v] of this)
callbackFn.call(thisArg, v, k, this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment