JavaScript WTF #5: no map() for iterables

In the last few days I did some formal reading and informal experimenting with EcmaScript6, and compiled the list of its most annoying “features”.

The fifth place goes to complete lack of standard functions for iterables. EcmaScript 6 introduces a lot of cool stuff, but it brings a fair share of new WTFs, and adds new thrill to some existing ones. ES6 defines the concept of iterable and the for..of loop. You can now write something like this:

// iterable
function *range(start, len) {
    for (var i=start; i<start+len; ++i) yield i;
}

for (var n of range(3,4)) console.log(n); // prints 3 4 5 6 

Most languages that define iterables (a.k.a enumerables, sequences, comprehensions) come with standard methods that operate on them, such as map(), filter(), or groupBy(), but JavaScript has none. It does have map(), filter(), reduce(), but only for arrays:

var arr = Array.from(range(1,10));
console.log(arr);             // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
console.log(arr.map(n=>n*n)); // [ 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 ]

console.log(...range(1,10));  // 1 2 3 4 5 6 7 8 9 10
console.log(...range(1,10).map(n=>n*n)); // error

Of course, one can define necessary functions with relative ease, but their omission from the standard is very annoying. Most articles on iterables simply ignore the subject. I found a library called wu.js that claims to implement them, but their ES6 download link is broken. There is also a library called functify. I also found comments from several people that said they tried to write a similar library and it was fun, but the result was horribly inefficient. If this is indeed the case, it makes iterables virtually useless.

1 Comment


  1. Sounds like an opportunity for someone to create an efficient library or to create a specification (and possibly an implementation) to add these features to ES7. Otherwise, I agree, not having these functions standardized does reduce the value of having iterables.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *