The above operations can be performed even with a simple forEach with less redundancy and confusion of accumulator,but the problem is not that.Coding in FP style doesn't mean writing multiple functionalities into single reduce or forEach, but is to separate the functionality into multiple functions which has a single predefined meaning(filter-filters out some elements,map-converts one type to another etc).
When we use reduce for filter and map and flattening etc its much harder to understand the code at a glance.
Also the typical javascript filter/map etc or lodash utils doesn't natively support chaining of functions. Java 8 streams support such chaining without reducing the performance.
Similarly there are multiple Utils/libraries which support chaining of multiple functions and execute them vertically so that performance will still be maintained.
The functionality is filter persons with age <30 and map to employee object
Eg : var persons = [{
name: 'abc',
age: 23,
profession: 'hhh'
},
{
name: 'def',
age: 35,
profession: 'xxx'
},
{
name: 'xyz',
age: 40,
profession: 'aaa'
}
];
var employees = Stream(persons).filter(person => {
console.log('filter', person);
return person.age > 30
}).map(person => {
console.log('map', person);
return {
name: person.name,
profession: person.profession
};
}).toArray();
console.log(employees);
The above code is written using Stream.js library winterbe.github.io/streamjs/
The above code exactly run 3 times and finishes filtering and map but lodash or other chaining utils takes 3 + 2 =5 times.(for above example).
Even a typical forEach loop with if condition works faster than lodash chaining.