0

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?

2
  • You have such odd restrictions. Is this homework? Commented Jun 18, 2015 at 17:35
  • None, a friend asked me and I found it interesting. Commented Jun 18, 2015 at 17:42

3 Answers 3

1
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' ]
);
Sign up to request clarification or add additional context in comments.

2 Comments

Creative, but certainly not very efficient as you end up with a function call for every argument.
@jfriend00 obviously not very efficient, but efficiency wasn't part of the brief :-)
0

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
    }
}

4 Comments

I do not want to use the apply function, since I am trying to implement it :)
You're not going to be able to then unless you know the number of arguments
So there is no general solution to this?
@jfriend00, args here is the array passed in not the built in arguments array.
0

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!

2 Comments

As I mention, I do not want to Function() which is kind of similar what eval() can do for us.
Without these there is no way. Why do you need this for?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.