Skip to content

Instantly share code, notes, and snippets.

@oliverjumpertz
Last active May 9, 2020 17:35
Show Gist options
  • Save oliverjumpertz/09b5ee70175e13554d775c1e46137fb5 to your computer and use it in GitHub Desktop.
Save oliverjumpertz/09b5ee70175e13554d775c1e46137fb5 to your computer and use it in GitHub Desktop.
once is a function wrapper that wraps another function. The wrapped function will only be executed exactly once, no matter what arguments are passed in subsequent calls.
type AnyFunc = (...args: any) => any;
export function once(func: AnyFunc): AnyFunc {
let alreadyCalled = false;
return (...args: any[]): any => {
if (alreadyCalled) {
return undefined;
}
alreadyCalled = true;
return func(args);
};
}
import { once } from './once';
function logSomething() {
console.log('something');
}
const logSomethingOnce = once(logSomething);
logSomethingOnce();
logSomethingOnce();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment