Last active
May 9, 2020 17:35
-
-
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.
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
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); | |
}; | |
} |
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
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