Skip to content

Instantly share code, notes, and snippets.

@micahasmith
Created December 29, 2011 01:17
reduce sum and product
/**
* Walk through a list, running an associative function on each item, and returning the result
* @param {function} func A function in the form of f(x,y) to be applied to each item and its successor in list
* @param {Object[]} list The array to have the function applied to
* @param The y value of an object passed into <tt>func</tt> when x is the last item in the list
* @returns An object containing the result of <tt>func</tt> applied to <tt>list</tt>
*/
var reduce=function(func,list,nilval) {
var len=list.length,
i=0,
r=nilval;
for(;i<len;i+=1) {
r=func(r,list[i]);
}
return r;
};
var add=function(x,y) {
return x+y;
};
var sum=function(list) {
return reduce(add,list,0);
};
var multiply=function(x,y) {
return x*y;
};
var product=function(list) {
return reduce(multiply,list,1);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment