Write your own map filter and reduce
Tuesday, July 16, 2019
So most of us know that these functions already exists.
[].map();
[].filter();
[].reduce();
But how do they work internally? It’s actually pretty easy. So let’s just write them ourselves. Cool
Map
function map(array, cb){
const result = [];
for(let i = 0; i < array.length; i++){
const item = array[i];
result.push(cb(item, i));
}
return result;
}
Map is pretty simple.
Filter
function filter(array, cb){
const result = [];
for(let i = 0; i < array.length; i++){
const item = array[i];
const check = cb(item, i);
if(check){
result.push(item);
}
}
return result;
}
Also not too tough.
Reduce
function reduce(array, cb, init){
let result = init;
for(let i = 0; i < array.length; i++){
const item = array[i];
result = cb(result, item, i);
}
return result;
}
Reduce is a little more involved but it isn’t anything too crazy. We just make sure to return what they passed last iteration to the next iteration.
Final note:
Interestingly enough. Reduce can be our base construct for all our other loops and we can use it to implement
map
and
filter
Map using reduce
function map(array, cb){
return reduce(array, (carry, item, i) => {
const result = cb(item, i);
carry.push(result);
return carry;
}, [])
}
Filter using reduce
function filter(array, cb){
return reduce(array, (carry, item, i) => {
const check = cb(item, i);
if(check){
carry.push(result);
}
return carry;
}, []);
}
Anyway don’t roll your own reduces and maps unless you have a good reason. But it is nice to know how things work at a lower level. That way you can better utilize them in the future.
Thanks for reading.