patternjavascriptMinor
Better way to write this code in functional manner using map and reduce?
Viewed 0 times
thismapandwayfunctionalwritebettermannerreduceusing
Problem
I have an array of items on which I have to perform 2 tasks:
The functional approach to solving this would be
But here the array
Isn't the functional approach bad in this case or am I not using
- Applying a function on the array item
- Checking if the value is true or false.
The functional approach to solving this would be
var result = arr.map(function(item){return some_action(item);}).filter(function(item){return other_action(item) == true;});But here the array
arr is traversed twice in comparison to var result = [];
arr.forEach(function(item){
var x = other_action(some_action(item));
if (x)
result.push(x);
});Isn't the functional approach bad in this case or am I not using
map and filter the right way?Solution
Your “functional” approach is overly complicated. Notice that this is completely equivalent:
I.e. If you're only delegating to another function, you can specify that function directly. Also, an
Your “procedural” variant is not equivalent, that would have to be:
Note that both variants have the same algorithmic complexity, and that the cost of iteration is likely negligible compared with the cost of
Functional programming does not mean unreadable code. Even if you're not just delegating to another function, you could improve formatting, e.g. to
var result = arr.map(some_action).filter(other_action);I.e. If you're only delegating to another function, you can specify that function directly. Also, an
== true test is superfluous.Your “procedural” variant is not equivalent, that would have to be:
var result = [];
arr.forEach(function(item){
var changedItem = some_action(item);
if (other_action(changedItem))
result.push(changedItem);
});Note that both variants have the same algorithmic complexity, and that the cost of iteration is likely negligible compared with the cost of
some_action and other_action.Functional programming does not mean unreadable code. Even if you're not just delegating to another function, you could improve formatting, e.g. to
var result = arr.map(function (item) {
return some_action(item);
}).filter(function (item) {
return other_action(item);
});Code Snippets
var result = arr.map(some_action).filter(other_action);var result = [];
arr.forEach(function(item){
var changedItem = some_action(item);
if (other_action(changedItem))
result.push(changedItem);
});var result = arr.map(function (item) {
return some_action(item);
}).filter(function (item) {
return other_action(item);
});Context
StackExchange Code Review Q#40541, answer score: 8
Revisions (0)
No revisions yet.