Reputation: 451
I was in a seminar where a discussion was brought up about using _.each() to do _.reduce(), _.map(), and _.filter() as an exercise to understand the concepts better.
I'm not even totally sure what this means, but I'm wondering if someone could clear this up for me? How would one go about using _.each() to do _.reduce(), _.map(), and _.filter()?
Sorry if this is vague.
Upvotes: 0
Views: 285
Reputation: 337
Let's take _.map
as an example. _.map
iterates over a collection, executing a function (iteratee) per item on that collection, building a new array out of the iteratee's return values.
_.map( [ 1, 2, 3 ], function ( val ) {
return val * 2;
});
outputs [ 2, 4, 6 ]
To recreate the _.map functionality using _.each
you could do something like this:
function map ( arr, iteratee ) {
var newArray = [];
_.each( arr, function ( val ) {
newArray.push( iteratee( val ) );
}
return newArray;
}
And you would use it like this:
map( [ 1, 2, 3 ], function ( val ) {
return val * 2;
});
Upvotes: 1