5

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?

Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76
mukesh210
  • 2,792
  • 2
  • 19
  • 41
  • I have no idea, but I really want to learn that!!! Very good question. – Giorgos Papageorgiou Jul 15 '19 at 15:09
  • 1
    You're basically asking about transducers? Like https://github.com/cognitect-labs/transducers-js or RamdaJS (and many others)? As described in https://medium.com/@roman01la/understanding-transducers-in-javascript-3500d3bd9624? (The web is your friend. I searched for "javascript fp don't create intermediate collections".) – Dave Newton Jul 15 '19 at 15:18
  • @DaveNewton yes... i already visited above link... but is it possible to achieve something useful without above library. – mukesh210 Jul 15 '19 at 15:20
  • @MukeshPrajapati Sure, implement it the way they do--the source is trivially available for study. – Dave Newton Jul 15 '19 at 15:21

1 Answers1

3

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.

Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76