Skip to content

Instantly share code, notes, and snippets.

@JoelCodes
Created May 31, 2017 19:36
Show Gist options
  • Select an option

  • Save JoelCodes/90e70bc425967b8920c934275d179e60 to your computer and use it in GitHub Desktop.

Select an option

Save JoelCodes/90e70bc425967b8920c934275d179e60 to your computer and use it in GitHub Desktop.
/**
*
* @param {array} target
* @param {function} cb: (oldAcc, item, index) -> newAcc
* @param {*} seed
*/
function reduce(target, cb, seed){
var runningAggregate = seed;
target.forEach(function(item, index){
runningAggregate = cb(runningAggregate, item, index);
});
return runningAggregate;
}
// console.log(reduce([3, 4, 5], function(acc, val){
// return acc + val;
// }, 0), 3);
function sum(arr){
var runningTotal = 0;
arr.forEach(function(item){
runningTotal += item;
});
return runningTotal;
}
function sumFromReduce(arr){
return arr.reduce(function(runningTotal, item){
console.log('Iteration', runningTotal, item);
return runningTotal + item;
}, 0);
}
function maxFromReduce(arr){
return reduce(arr, function(runningMax, item){
console.log('Iteration', runningMax, item);
if(runningMax > item) return runningMax;
else return item;
}, -Infinity);
}
console.log('Total Sum:', sumFromReduce([3, 4, 5]));
console.log('Total Max:', maxFromReduce([4, 3, 5]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment