0

I'm trying to implement a function that takes another function as an argument, and returns a new version of that function that can only be called once.

Subsequent calls to the resulting function should have no effect (and should return undefined).

For example:

logOnce = once(console.log) 
logOnce("foo") // -> "foo" 
logOnce("bar") // -> no effect
6
  • Do you have a working fiddle to illustrate your question? Because as is, we cannot understand it... Commented Oct 28, 2014 at 8:52
  • What's your question? Commented Oct 28, 2014 at 8:52
  • He want's a function who can run only one time. Commented Oct 28, 2014 at 8:53
  • Is once(console.log, "foo"); ok? Than it's easier. Commented Oct 28, 2014 at 8:55
  • here function once has the argument console.log, which is assigned to to the logOnce. So if i call logOnce("foo") it should return me same functionality as console.log("foo") does. But this should be invoked only once. Commented Oct 28, 2014 at 9:00

1 Answer 1

1

You can use a flag on the function obeject you are passing as argument

function once(func){
  return function(){
    if(!func.performed){
      func.apply(this,arguments);
      func.performed = true;
    }    
  }
}

var logOnce = once(console.log);
logOnce("Test 1");
logOnce("Test 2");

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer but it should run only once, second time should do nothing(or return undefined).
The second time it doesn't log infact

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.