Iterating over Harmony Maps

A while ago Chrome got some JavaScript Harmony features (behind a flag). One of these features is the new Map “class”. The current implementation does not provide a way to iterate over the keys or values because that depends on Harmony iterators which are not yet implemented in V8.

However, we can create our own class that adds support for iteration. I’ve uploaded a simple implementation to GitHub.

The implementation creates a new “class” since V8 does not correctly allow sub classing of Map. The name of this “class” is ForEachMap since it provides one additional method over the standard Map, a forEach method. The forEach method calls a function for every key-value pair in the map.

Usage:

var map = new ForEachMap;
map.set('a', 'A');
map.set('b', 'B');
map.forEach(function(value, key) {
  console.log(key, value); 
});

The iteration order is the same as the key-value pair creation order. Changes to the map is allowed during iteration and deleted keys are guaranteed to not be visited and new keys will be visited in the current iteration.

The implementation uses a WeakMap as a side table for the private state of the map. The private state contains arrays with keys and values and a real Map that maps the key to the given index. It also keeps track of number of holes in these arrays so that we can reindex the arrays when there are too many holes.

This wrapper is of course unfortunate but at least it makes the Map “class” more useful while we wait for implementations to add support for native iteration.