Last active
January 16, 2018 02:53
-
-
Save gabemeola/67df40a9d3cfa67211b9dabadf748e7e to your computer and use it in GitHub Desktop.
Caches a function call to be in lazily invoked just 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
/** | |
* Takes a function a lazily runs it once when invoked. | |
* | |
* Returns cached return value to subsequent calls. | |
* Return value will always have reference equality with subsequent calls. | |
* | |
* @param {function} func - Function to run Once | |
* @return {function} | |
*/ | |
export default function once(func) { | |
const neverRan = Symbol(); | |
let cacheReturn = neverRan; | |
return function onceRun(...args) { | |
if (cacheReturn === neverRan) { | |
cacheReturn = func(...args); | |
} | |
return cacheReturn; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tiny Version