Map using tuples or objects Map using tuples or objects javascript javascript

Map using tuples or objects


Ok, I've raised the issue on esdiscuss now and I got an answer from Mozilla's Jason Orendorff:

  1. This is a problem with ES6 maps.
  2. The solution will come in the form of ES7 value objects for keys instead of objects.
  3. It was considered before to let people specify .equals and .hashCode but it was rejected in favor of value objects. (for good reasons in my opinion).
  4. The only solution as of now is to roll your own collection.

A basic such collection (concept, don't use in production code) was offered by Bradley on the ESDiscuss thread and might look something like this:

function HashMap(hash) {  var map = new Map;  var _set = map.set;  var _get = map.get;  var _has = map.has;  var _delete = map.delete;  map.set = function (k,v) {    return _set.call(map, hash(k), v);  }  map.get = function (k) {    return _get.call(map, hash(k));  }  map.has = function (k) {    return _has.call(map, hash(k));  }  map.delete = function (k) {    return _delete.call(map, hash(k));  }  return map;}function TupleMap() {  return new HashMap(function (tuple) {    var keys = Object.keys(tuple).sort();    return keys.map(function (tupleKey) { // hash based on JSON stringification               return JSON.stringify(tupleKey) + JSON.stringify(tuple[tupleKey]);    }).join('\n');    return hashed;  });}

A better solution is to use something like MontageJS/Collections which allows for specification of hash/equals functions.

You can see the API docs here.


It doesn’t seem conveniently possible. What can you do? Something horrible, as always.

let tuple = (function() {    let map = new Map();    function tuple() {        let current = map;        let args = Object.freeze(Array.prototype.slice.call(arguments));        for (let item of args) {            if (current.has(item)) {                current = current.get(item);            } else {                let next = new Map();                current.set(item, next);                current = next;            }        }        if (!current.final) {            current.final = args;        }        return current.final;    }    return tuple;})();

And voilà.

let m = new Map();m.set(tuple(3, 5), [tuple(3, 5, 3), tuple(3, 5, 4)]);m.get(tuple(3, 5)); // [[3, 5, 3], [3, 5, 4]]


Benjamin's answer doesn't work for all objects, as it relies on JSON.stringify, which cannot handle circular objects and can map different objects to the same string. Minitech's answer can create huge trees of nested maps, which I suspect are both memory and CPU inefficient, especially for long tuples, as it has to create a map for each element in the tuple.

If you know that your tuples only contain numbers, then the best solution is to use [x,y].join(',') as the key. If you want to use tuples containing arbitrary objects as keys, you can still use this method, but have to map the objects to unique identifiers first. In the code below I generate these identifiers lazily using get_object_id, which stores the generated ids in an internal map. I can then generate keys for tuples by concatenating those ids. (See code at the bottom of this answer.)

The tuple method can then be used to hash tuples of objects to a string that can be used as the key in a map. This uses object equivalence:

x={}; y={}; tuple(x,y) == tuple(x,y) // yields truetuple(x,x) == tuple(y,y) // yields falsetuple(x,y) == tuple(y,x) // yields false

If you're certain that your tuples will only contain objects (i.e. not null, numbers or strings), then you can use a WeakMap in get_object_id, such that get_object_id and tuple won't leak objects that are passed as argument to them.

var get_object_id = (function() {  var generated_ids = 1;  var map = new Map();  return get_object_id;  function get_object_id(obj) {    if (map.has(obj)) {      return map.get(obj);    } else {      var r = generated_ids++;      map.set(obj, r);      return r;    }  }})();function tuple() {  return Array.prototype.map.call(arguments, get_object_id).join(',');}// Testvar data = [{x:3,y:5,z:3},{x:3,y:4,z:4},{x:3,y:4,z:7},            {x:3,y:1,z:1},{x:3,y:5,z:4}];var map = new Map();for (var i=0; i<data.length; i++) {  var p = data[i];  var t = tuple(p.x,p.y);  if (!map.has(t)) map.set(t,[]);  map.get(t).push(p);}function test(p) {  document.writeln((JSON.stringify(p)+' ==> ' +     JSON.stringify(map.get(tuple(p.x,p.y)))).replace(/"/g,''));}document.writeln('<pre>');test({x:3,y:5});test({x:3,y:4});test({x:3,y:1});document.writeln('</pre>');