I have been reading about map, reduce and filter a lot because of how much they are used in react and FP in general. If we write something like:
let myArr = [1,2,3,4,5,6,7,8,9] let sumOfDoubleOfOddNumbers = myArr.filter(num => num % 2) .map(num => num * 2) .reduce((acc, currVal) => acc + currVal, 0); 3 different loops are run.
I've read about Java 8 streams as well and know that they use what is called a monad, ie, the computations are stored first. They are performed once only in one iteration. For example,
Stream.of("d2", "a2", "b1", "b3", "c") .map(s -> { System.out.println("map: " + s); return s.toUpperCase(); }) .filter(s -> { System.out.println("filter: " + s); return s.startsWith("A"); }) .forEach(s -> System.out.println("forEach: " + s)); // map: d2 // filter: D2 // map: a2 // filter: A2 // forEach: A2 // map: b1 // filter: B1 // map: b3 // filter: B3 // map: c // filter: C PS: Java code is taken from: http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
There are many other languages that use this same method. Is there a way to do it the same way in JS as well?
_.chainmyArr.reduce((acc, num) => num % 2 ? acc += num * 2 : acc, 0);