Using JS array functions on a ES6 iterable

Viewed 53

I really like the simplicity and expressiveness of JS Array object functions such as map(), filter(), reduce(), some(), every(), etc. They allow to create very concise yet clear code manipulating data structures.

I am also a big fan of EC6 iterator protocol. It makes the code readable through the use of (... of ...) {...} statements, and standard collections like Map and Set support it well.

However, coming from Java background I used to expect consistency in the way collection frameworks are put together, and I find it very frustrating that there is no way to use functions like map() or filter() on an iterator. Yes, one can use the splice operator and write a code like this: [...iterable].filter(...), but it's not great. Such code looks less clear, and, moreover, you end up allocating memory for arrays. This is particularly problematic if you expect to filter out most of the values. Also if you are chaining the functions, all intermediate results would also be arrays that require memory to be allocated and values copied into.

My question is whether there a way to write clear and concise code in JavaScript (or TypeScript) that would use iterables/generators on one hand, and functions that behave like the array functions above on the other? I am open to options that require the use of some third-party library or a transpiler. All I care about here is to write code as clear as possible.

Edit: to be clear I am not looking for a way to lazily apply filter and map logic over a collection/iterable specifically. It was just an illustration. I am looking for a way to write readable yet efficient code using array-like functions over iterables. Whilst is is possible to muck about with the Iterator prototype in the code, there will be bugs I will introduce inevitably, and I would much rather use a library that does it with the benefit of many eyes behind it.

0 Answers
Related