Skip to content

Instantly share code, notes, and snippets.

@jewel-andraia
Last active December 10, 2015 23:48
Show Gist options
  • Save jewel-andraia/4511973 to your computer and use it in GitHub Desktop.
Save jewel-andraia/4511973 to your computer and use it in GitHub Desktop.
aggregator meta-function for JavaScript
Function.prototype.aggregate = function(initial, array) {
var callback = this;
var val = initial;
for (var i = 0; i < array.length; i++) {
val = callback(val, array[i], key);
}
return val;
}
Function.prototype.aggregateObject = function(initial, obj) {
var callback = this;
var val = initial;
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
val = callback(val, obj[i], i);
}
return val;
}
// aggregatable functions look like:
// function(currentValue, nextItem, nextItemKey) {
// return /* aggregation of currentValue and nextItem */;
// }
function sum(current + next) {
return current + next;
}
var array = [1, 2, 3, 4, 5];
console.log(sum.aggregate(0, array));
// returns 15
var obj = { a: 1, b: 2 };
console.log(sum.aggregateObject(0, obj));
// returns 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment