Skip to content

Instantly share code, notes, and snippets.

@stefanfrede
Last active June 10, 2016 05:36
Show Gist options
  • Save stefanfrede/fa4318be0fb9b058f39b2c4739001410 to your computer and use it in GitHub Desktop.
Save stefanfrede/fa4318be0fb9b058f39b2c4739001410 to your computer and use it in GitHub Desktop.
Once ensures that a function can only be called once.
/**
* 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