Last active
September 25, 2020 10:06
-
-
Save Cologler/48901bdaf77b306df22400c2cbd8987e to your computer and use it in GitHub Desktop.
Replacement for npm package onetime and 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
/* Copyright (c) 2020~2999 - Cologler <[email protected]> */ | |
/** | |
* Run a function exactly one time. | |
* | |
* @param fn {Function} | |
*/ | |
function once(fn) { | |
let called; | |
let value; | |
return function () { | |
return called | |
? value | |
: (called = true) && (value = fn.apply(this, arguments)); | |
} | |
} |
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
/* Copyright (c) 2020~2999 - Cologler <[email protected]> */ | |
/** | |
* Run a function exactly one time. | |
* | |
* @param fn {Function} | |
*/ | |
function once<TArgs extends any[], TResult>(fn: (...TArgs) => TResult): (...TArgs) => TResult { | |
let called: boolean = false; | |
let value: TResult; | |
return function () { | |
return called | |
? value! | |
: (called = true) && (value = fn.apply(this, arguments)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment