Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / Javascript

JavaScript WTF #5: No map() for Iterables

Rate me:
Please Sign up or sign in to vote.
4.60/5 (3 votes)
30 Dec 2016Apache1 min read 11.2K  
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.

This article was originally posted at http://www.ikriv.com/blog?p=2186

License

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


Written By
Technical Lead Thomson Reuters
United States United States
Ivan is a hands-on software architect/technical lead working for Thomson Reuters in the New York City area. At present I am mostly building complex multi-threaded WPF application for the financial sector, but I am also interested in cloud computing, web development, mobile development, etc.

Please visit my web site: www.ikriv.com.

Comments and Discussions

 
-- There are no messages in this forum --