Maps with object keys
C. Scott Ananian
ecmascript at cscott.net
Mon Feb 17 14:20:29 PST 2014
It is straightforward to implement a hash function based map as a
subclass of `Map`. Something like:
```js
var HashMap = function() { this._map = new Map(); };
HashMap.set = function(key, value) {
var hash = key.hashCode();
var list = this._map.get(hash);
if (!list) { list = []; this._map.set(hash, list); }
for (var i=0; i<list.length; i++) {
if (list[i].key.equals(key)) {
list[i].value = value;
return;
}
}
list[i].push({key: key, value: value });
};
// etc
```
(For simplicity I used delegation above, rather than a subclass, and I
used ES5 syntax.)
Note that the above implementation makes a number of assumptions which
the ES6 designers decided were *not* appropriate to hardcode into the
language:
1. All object used as keys must implement `hashCode` and `equals` with
appropriate semantics.
2. Hash code collisions cause the map to revert to linear search.
(Alternatively you could implement a different variant of hashtable
chaining.)
ES6 includes only the basic `Map` primitive, on top of which you can
build the infinite variety of different `Map` variants.
I expect that we will begin to see helper libraries built on top of
ES6 primitives. As an example, I wrote `prfun` to provide
Promise-related helpers on top of the (similarly bare-bones) ES6
`Promise`. Presumably we'll eventually see some library with a name
like `javamap` to provide java-style `hashCode`/`equals` maps on top
of ES6 `Map` for those who want that.
--scott
More information about the es-discuss
mailing list