Since Array.from
does not work on Chrome at the current time, I needed another way to convert an Iterator into an Array.
(though of course you can shim it with a polyfill)
function iterator2Array(iterator) {
var result = [];
for (var item in iterator) {
result.push(item)
}
return result;
}
For similar reasons I add a "toArray" to the prototype of a Map so that I basically convert an iterator into an Array so that you can use its functional-oriented methods; of course each item of the array will be a [key, value] tuple (exactly like in its Map.entries()
)
if (!Map.prototype.toArray) {
/**
* Transforms a map into an Array of 'tuples' [[key, value], ...]
*/
Map.prototype.toArray = function () {
var result = [];
for (var item of this) {
result.push(item);
}
return result;
}
}
var m = new Map([[0, 0], ['a', 'A']]);
m.toArray()
Then you can use it as an array - remember the [key, value] approach though!
m.toArray().map(
function(item, index, array) {
var key = item[0],
value = item[1];
console.log(key + ": " + value);
return value;
});
This will return the values of the map (ok not superuseful of course!)
If you prefer a more standar looking loop:
var i = iterator.entries(),
result = [],
value;
while (value = i.next().value) {
result.push(value);
}