Last active
December 10, 2015 23:48
-
-
Save jewel-andraia/4511973 to your computer and use it in GitHub Desktop.
aggregator meta-function for JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 */; | |
// } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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