Last active
June 10, 2016 05:36
-
-
Save stefanfrede/fa4318be0fb9b058f39b2c4739001410 to your computer and use it in GitHub Desktop.
Once ensures that a function can only be called once.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* You pass it a function, and you get a function back. | |
* That function will call your function once, and | |
* thereafter will return undefined whenever it is | |
* called. | |
*/ | |
const once = (fn) => { | |
let done = false; | |
return function () { | |
return done | |
? void 0 | |
: ((done = true), fn.apply(this, arguments)); | |
}; | |
}; | |
/** | |
* Examples: | |
*/ | |
const askedOnBlindDate = once( | |
() => "sure, why not?" | |
); | |
askedOnBlindDate(); | |
//=> 'sure, why not?' | |
askedOnBlindDate(); | |
//=> undefined | |
askedOnBlindDate(); | |
//=> undefined | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment