Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

JavaScript WTF #5: No map() for Iterables

4.60/5 (3 votes)
30 Dec 2016Apache1 min read 11.3K  
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:

JavaScript
// 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:

JavaScript
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.

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0