posted 6 years ago
With newer versions of ECMA, Javascript has added functional programing methods to the Array prototype. By functional programing methods, I mean things like map, reduce, forEach, filter (select), every (all), some (any), etc. Maybe stream methods is a better designation. This means that JavaScript arrays can now be considered, by functional programing terminology, functors. So that's good.
ECMA has also added generator functions, so it is now possible to define finite or even infinite streams of values. The values can be lazily calculated as needed, so they are great for things like a Fibonacci sequence or a prime number generator, but also have more everyday applications. So that's good too. However, it's not possible to call map, reduce, or any of the cool new Array methods on a generator. (Yes, some wouldn't make sense on an infinite series, but adding take and takeWhile would solve that.)
Now JavaScript is so malleable that it seems to me I should be able to compensate for this lack by just implementing the methods myself. I just can't find the right prototype to add these methods to. Is there any way to do it? If not, has there been any discussion of adding these abilities to generators in the future?
Note: it's easy enough to implement a library of these methods that take the generator or array as a parameter. The wu library has taken this approach, and it's fine, but when the methods are chained together, which is part of their power, then readability suffers. In fact, the chain becomes more understandable by reading it bottom to top or right to left. Python, despite being a generally clean and well-designed language, also has this problem.