Using Array objects as key for ES6 Map
I also had this need, so I wrote an ISC-licensed library: array-keyed-map. You can find it on npm. I think the source is quite clear, but here's how it works anyway, for posterity:
Maintain a tree of Map
objects. Each tree stores:
Under an internally-declared
Symbol
key: The value at that point in the tree (if any). TheSymbol
guarantees uniqueness, so no user-provided value can overwrite this key.On all its other keys: all other so-far set next-trees from this tree.
For example, on akmap.set(['a', 'b'], true)
, the internal tree structure would be like—
'a':
[value]: undefined
'b':
[value]: true
Doing akmap.set(['a'], 'okay')
after that would just change the value for the path at 'a'
:
'a':
[value]: 'okay'
'b':
[value]: true
To get the value for an array, iterate through the array while reading the corresponding keys off the tree. Return undefined
if the tree at any point is non-existent. Finally, read the internally declared [value]
symbol off the tree you've gotten to.
To delete a value for an array, do the same but delete any values under the [value]
-symbol-key, and delete any child trees after the recursive step if they ended up with a size
of 0.
Why a tree? Because it's very efficient when multiple arrays have the same prefixes, which is pretty typical in real-world use, for working with e.g. file paths.
Understand that ES2015 Map keys are compared (almost) as if with the ===
operator. Two array instances, even if they contain the same values, do not ever compare as ===
to each other.
Try this:
var a = new Map(), key = ['x', 'y'];
a.set(key, 1);
console.log(a.get(key));
Since the Map class is intended to be usable as a base class, you could implement a subclass with an overriding .get()
function, maybe.
(The "almost" in the first sentence is to reflect the fact that Map key equality comparison is done via Object.is()
, which doesn't come up much in daily coding. It's essentially a third variation on equality testing in JavaScript.)
You need to save a reference to the non-primitive instance of Array
you used as a key. Notice the difference in the following two examples:
"use strict";
var a = new Map();
a.set(['x','y'], 1);
console.log(a.get(['x','y']));
console.log(['x','y'] === ['x','y']);
var b = new Map();
var array = ['x','y'];
b.set(array, 1);
console.log(b.get(array));
console.log(array === array);