What is the most idiomatic way to call all functions in a list?
The best I can think of is:
myFunctions.forEach(function(f){f();});
Is there a more idiomatic way of doing this?
EDIT:
I'm really only interested in ES5 for now. Perhaps there is some way having to do with Array prototypes?
What about ES6? You can use arrow function.
This would be :
myFunctions.forEach( f => f());
You can already use it today with tool like babel. For an overview of ES6 features check out es6features.
EDIT:
You can extend the Array
object with the following method:
Array.prototype.invokeFunctions = function () {
this.forEach(function (f) {
if (typeof(f) === "function")
f()
});
}
var functions = [
function () { console.log(1);},
function () { console.log(2);}
];
functions.invokeFunctions();
// output
1
2
However, I don't think this is a good idea as it pollutes the global Array prototype. A better idea could be to use an object designed explicitly for this purpose. For example:
function FunctionList(functions) {
this.functions = functions;
}
FunctionList.prototype.callAll = function () {
this.functions.forEach(function (f) {
if (typeof(f) === "function")
f()
});
}
var functionList = new FunctionList(functions);
functionList.callAll();
This is a better solution in my opinion. Every time you have a function array you can wrap it in a FunctionList
object. However in this case you lose all the benefits of using an Array and you have to implement getter and setter methods if you want to modify/access the function array.
You could get tricky and use prototype methods, though it's not much more succinct:
myFunctions.map(Function.prototype.call, Function.prototype.call);
a wee bit shorter if you grab a reference to call:
var call = Function.prototype.call;
myFunctions.map(call, call);
or we could go nuts with prototype methods:
[].map.apply(fns, [call, call]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With