I do not care much about the context and I do not want to use Function(). The function should take a function and an array of parameters. Example
apply(fn, args) => fn(args[0], args[1], ..., args[args.length-1]);
Is it even possible?
I do not care much about the context and I do not want to use Function(). The function should take a function and an array of parameters. Example
apply(fn, args) => fn(args[0], args[1], ..., args[args.length-1]);
Is it even possible?
var apply = function(fn, args) {
var _fn = fn;
args.forEach(function(arg) {
_fn = _fn.bind(null, arg);
});
return _fn();
};
apply(
function() { console.log(arguments); },
[ 'arg 1', 'arg 2', 'arg 3', 'arg 4' ]
);
If you don't know the number of args then this is the only way:
function apply(fn, args) {
return fn.apply(null, args);
}
if you know the number (say 2):
function apply(fn, args) {
return fn(args[0], args[1]);
}
Or:
function apply(fn, args) {
switch (args.length) {
case 0:
return fn();
case 1:
return fn(args[0]);
case 2:
return fn(args[0], args[1]);
case 3:
return fn(args[0], args[1], args[2]);
// etc
}
}
There is a very nasty solution using eval:
function apply(fn, args) {
var a = [];
for (var i = 0; i < args.length; i++){
a.push("args["+i+"]");
}
command_string = "function inner_apply(fn, args) { return fn(" + a.join(",") + ");} ";
eval(command_string);
return inner_apply(fn, args);
}
Please never use this is real life!