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
Vishwa
  • 134
  • 3
  • 3
  • 14
  • Do you have a working [fiddle](http://jsfiddle.net/) to illustrate your question? Because as is, we cannot understand it... – sp00m Oct 28 '14 at 08:52
  • What's your question? – Clive Oct 28 '14 at 08:52
  • He want's a function who can run only one time. – Andreas Furster Oct 28 '14 at 08:53
  • Is `once(console.log, "foo");` ok? Than it's easier. – Andreas Furster Oct 28 '14 at 08: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. – Vishwa Oct 28 '14 at 09:00
  • @AndreasFurster ty for you reply, nope it should take only the function as an argument the value will be passed when it's invoked with the other function. – Vishwa Oct 28 '14 at 09:05

1 Answers1

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");