MapReduce: Functional programming with Node.JS
In the
context of big data, it is often normal we have arrays with thousand entries.
And operations to filter, transform (map) or calculate statistics indicators
(reduce) had to be often performed.
However,
without techniques of functional programming, one of few alternatives is to
program that using loops, such as for statements, while statements, or do-while statements.
However
with map reduce techniques we can focus just in specific functions to be
programmed, according with the business rule, and all the complexity to handle
big datasets, such as memory consumption and another optimizations are
performed by the own technology.
The first function we are going to study, is the filter function. Basically it has to receive a function as parameter. This function receives as parameter a current element (it will be executed for each array element) and return a Boolean value. If true the value is maintained in the output value, and if false it will not be presented in the output array. The filter function will produces a new array with filtered elements.
//filter
console.log("---Filter Method---");
let newArrayFiltered=arrayB.filter((el, index, array)=>{
if(typeof(el)!= "undefined"){
return true;
}else{
return false;
}
});
console.log("Filtered", newArrayFiltered);
The second
function is the map. It also receives as a parameter another function, that
receives as parameter the current element, and produces as output he same
element, but transformed. It means a new value to be placed in the same index
as the current value, but transformed. The output of the map function is an
array with the same length as the original array, but with elements
transformed.
//map
console.log("---Map
Method---");
let newArrayMapped=newArrayFiltered.map((el, index, array)=>{
return el*2;//double array values
});
console.log("Mapped", newArrayMapped);
The last
function we are going to study is the reduce. It basically will transform all
values of an array in a new value, normally a scalar value, it could be a sum,
mean, median standard deviation, and so on.
//reduce
console.log("---Reduce
Method---");
let reducedValueSum=newArrayMapped.reduce((prevVal, el)=>{
return prevVal+el;//sum all elements
});
console.log("Reduced
- SUM", reducedValueSum);
The source code
is available in github:
You can watch a
video class about these functions in this video below:
Comments
Post a Comment