Consider the following example
function doSomethingToAVariable(variable){
return variable + 1
}
function doSomethingToAVariableASecondTime(variable){
re
In my humble opinion, your code is perfectly fine.
But, you can do something like this if you really want to "chain" the calls. It is a bit less efficient though.
function chainCalls(initVal, funcs){
return funcs.reduce(function(val, f){
return f(val);
}, initVal || 0);
}
function doSomethingToAVariable(variable){
return variable + 1
}
function doSomethingToAVariableASecondTime(variable){
return variable + 2
}
function doSomethingToAVariableLastly(variable){
return variable + 3
}
var myVariable = chainCalls(0, [doSomethingToAVariable,
doSomethingToAVariableASecondTime,
doSomethingToAVariableLastly]);
document.write(myVariable);
Another alternative is to create a reusable function chain like this.
function functionChain(){
var funcs = arguments;
return function(value){
return Array.prototype.reduce.call(funcs, function(value, f){
return f(value);
}, value);
};
}
function doSomethingToAVariable(variable){
return variable + 1
}
function doSomethingToAVariableASecondTime(variable){
return variable + 2
}
function doSomethingToAVariableLastly(variable){
return variable + 3
}
var myVariable = functionChain(
doSomethingToAVariable,
doSomethingToAVariableASecondTime,
doSomethingToAVariableLastly
)(0);
document.write(myVariable);