Skip to content

Instantly share code, notes, and snippets.

@Cologler
Last active September 25, 2020 10:06
Show Gist options
  • Save Cologler/48901bdaf77b306df22400c2cbd8987e to your computer and use it in GitHub Desktop.
Save Cologler/48901bdaf77b306df22400c2cbd8987e to your computer and use it in GitHub Desktop.
Replacement for npm package onetime and once.
/* 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));
}
}
/* 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