In Scala, view
allows preventing creating an entirely new collection.
e.g. In Scala, what does "view" do?
Is there something similar in JavaScript? My use case:
x = inputValue.split(",").map(x => x.trim()).filter(f1).map(f2)
As you can see in the above code, 2 intermediate collections would be created. Is there some way in JavaScript to avoid creating the above intermediate collections?
Scala is a strict language similarily to Javascript. That means that if you create a list and use map, then Scala would eagerly create a new list:
//it creates List(2,3,4) and List(4,6,8) already when map is called
List(1,2,3).map(_ + 1).map(_ *2)
You can make Scala collections lazy though by calling view:
val l = List(1,2,3).view.map(_ + 1).map(_ * 2) //nothing happens yet
l.take(2) //only 1 and 2 get processed
Unfortunately, there is no built-in function in Javascript to make array behave lazily, but there is a library Lazy.js, which works similarly to Scala view:
Lazy([1,2,3]).map(x => x + 1).map(x => x * 2).take(2).toArray()
And according to docs:
What's important here is that no iteration takes place until you call each, and no intermediate arrays are created.