Let's say I have a list of functions stored in an array:
var myFunctions = [
function (i) {return i + 2},
function (i) {return i * 2},
function (i) {return i - 3}
]
What would be the best way to successively call all these functions an object, i.e. to get ((n + 2) * 2) - 3
as a result?
Answers using external libraries like Underscore are welcome :)
Arrays are also JavaScript objects. In your case, you created an array and three properties to it, namely f1
, f2
and f3
. Instead, you can simply do
var myFunctions = [
function(i) {
return i + 2
},
function(i) {
return i * 2
},
function(i) {
return i - 3
}
];
Now that we have an array of functions, we can use Array.prototype.reduce
function to apply these functions like this
var result = myFunctions.reduce(function(result, currentFunction) {
return currentFunction(result);
}, n);
The n
is the actual initial value to be passed to the list of functions to be applied. reduce
takes the initial value and the first function and passes them as the result
and currentFunction
respectively. We apply the currentFunction
on result
and return the value. In the next iteration, the returned value will be the result
and the currentFunction
will be the second function and so on.
If you don't like the functional approach, you can simply use a for loop, like this
var i = 0, result = 0, n = 10;
for (var i = 0; i < myFunctions.length; i += 1) {
n = myFunctions[i](n);
}