Created
July 13, 2019 18:38
-
-
Save monkeymonk/a1d2862858e192cf9fb21041d751123e to your computer and use it in GitHub Desktop.
Memoization helper
This file contains 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
/** | |
* Memoization helper. | |
* @param fn | |
* @param context | |
* @return Function | |
*/ | |
export default function memoize(fn, context = null) { | |
const cache = {}; | |
return (...args) => { | |
const key = JSON.stringify(args); | |
if (typeof cache[key] === 'undefined') { | |
if (fn === null || typeof fn === 'number' || typeof fn === 'undefined' || typeof fn.call === 'undefined') { | |
cache[key] = fn; | |
} else { | |
cache[key] = fn.call(context, ...args); | |
} | |
} | |
return cache[key]; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment