0

This is a problem that I know is simple, yet I'm stuck. If you could help me figure out what's missing in my code, I would appreciate it. I need to pass two tests 1) should execute function after specific wait time and 2) should have successfully passed function arguments in. The instructions are below as is my code. My issue here is that the code passes the first test but it doesn't pass the second one.

Instructions:

"Delays a function for the given number of milliseconds, and then calls it with the arguments supplied. The arguments for the original function are passed after the wait parameter. For example _.delay(someFunction, 500, 'a', 'b') will call someFunction('a', 'b') after 500ms"

My code:

_.delay = function(func, wait) {
    return setTimeout(function(){
        return func.call(this, arguments);
    }, wait);
};
insertusernamehere
  • 21,742
  • 7
  • 80
  • 113

1 Answers1

2

as you said:

The arguments for the original function are passed after the wait parameter. For example _.delay(someFunction, 500, 'a', 'b') will call someFunction('a', 'b') after 500ms"

what you are doing is not someFunction('a','b') but someFunction(someFunction, wait,'a','b')

so what you need to do is take all the parameters except the first 2 which can be done by doing var args = Array.prototype.slice.call(arguments,2)

and because you are passing an array you will need to use apply instead of call. Related question about the difference between call and apply

so you final code would be like this:

_.delay = function(func, wait) {
    var args = Array.prototype.slice.call(arguments,2);
    return setTimeout(function(){
        return func.apply(this, args);
    }, wait);
};

and you can always look at the annotated source of underscorejs

Community
  • 1
  • 1
grabthefish
  • 944
  • 18
  • 27