Polyfill of Array.reduce
Used to perform different types of actions like segregation, aggregation, running things in sequence/series etc.
Array.reduce((prevValue, currValue, currIndex, arr) => {
const nextValue = previousValue + currentValue;
return nextValue;
}, initialValue)
Aggregation
[1, 2, 3, 4].reduce((prevValue, currValue) => {
const nextValue = previousValue + currentValue;
return nextValue;
}, 0)
// Output: 10
Segregation
[1.1, 1.2, 1.3, 2.2, 2.3, 2.4].reduce((prevGroup, currValue) => {
if(!prevGroup[Math.floor(currValue)]){
prevGroup[Math.floor(currValue)] = []
}
prevGroup[Math.floor(currValue)].push(currValue)
return prevGroup
}, {})
// Output: { "1": [1.1, 1.2, 1.3], "2": [2.2, 2.3, 2.4]
Run in sequence
function upperCase(str) {
return str.toUpperCase();
}
function reverse(str) {
return str.split("").reverse().join("");
}
function removeLastLetter(str) {
return str.slice(0, -1);
}
const ans = [upperCase, reverse, removeLastLetter].reduce((prevValue, currValue) => {
let newValue = currValue(prevValue);
return newValue;
}, "nujra");
console.log(ans);
// Output: ARJU
Run the promise in sequence
function asyncTask(time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Completing" + time);
}, time * 100);
});
}
[asyncTask(3), asyncTask(7), asyncTask(1)].reduce((promise, curr) => {
return promise.then(() => {
return curr.then((val) => {
console.log(val);
});
});
}, Promise.resolve());