0

While solving a programming challenge, I wrote a function which was intended to take a function as an argument and return a function as well. The returned function was meant to execute the argument function (which was passed to first function). The function's code :-

function func1(f){
  let func2 = function(){
    if(/*a condition based on a global variable*/){
      f();
    }
  }
  return func2;
}

This is currently not working and it raises an Illegal Invocation Type Error. I saw this question but I don't know how to relate it's answers to my code. So, my questions are :-

  • Why isn't my code working?
  • What can I do to make it work?


EDIT

I'm invoking the function like this :-

var someFunc = func1(alert);
someFunc("foo");
someFunc("bar");
Arjun
  • 1,061
  • 1
  • 10
  • 24

2 Answers2

2

You need to handle

  • the context of the function call
  • the arguments
  • the returned value

Here's an implementation:

function func1(f, context){
  let func2 = function(){
    if( some condition ){
      return f.apply(context, arguments);
    } // there probably should be some "else" behavior...
  }
  return func2;
}

With some example uses:

var fun = func1(console.log, console);
fun("A", 25); // logs "A", 25
fun = func1(alert);
fun("foo");   // alerts "foo"
Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
-1

Why don't you use var instead of let

function func1(f){
  var func2 = function(){
    if(/*a condition based on a global variable*/){
      f();
    }
  }
  return func2;
}
Mohit Bhardwaj
  • 8,005
  • 3
  • 29
  • 60