Skip to content

Instantly share code, notes, and snippets.

@ecounysis
Last active June 12, 2016 04:56
Show Gist options
  • Save ecounysis/57115cdf5c7fb171dcea88e46ba94ad1 to your computer and use it in GitHub Desktop.
Save ecounysis/57115cdf5c7fb171dcea88e46ba94ad1 to your computer and use it in GitHub Desktop.
a function to average the results of applying other functions in javascript
function fnAverage() {
// Accepts any number of functions as its arguments.
// Returns a function that averages all the argument functions.
// Argument functions can accept args. In which case, just pass them into the
// returned function at call time.
// Resulting function will error if called with fewer args
// than required by function requiring the most args.
/*
// Example:
function One(x, y) {
return x + y;
}
function Two(a, b) {
return a * b;
}
var AvgOneTwo = fnAverage(One, Two);
AvgOneTwo(10, 20) == 115;
AvgOneTwo(1, -4) == -3.5;
*/
var fns = arguments;
var len = fns.length;
return function() {
var args = arguments;
var tot = 0;
for (var i=0; i<fns.length; i++) {
tot += fns[i].apply(null, args);
}
return tot / fns.length;
}
}
// QUESTION:
// How can this concept be generalized to a generic combining of functions,
// where the the generalized function combinator accepts a list of functions and
// a combining function? The combining function tells it how to "summarize" or
// combine the result of the application of the argument functions?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment