Last active
December 5, 2020 23:39
-
-
Save behnammodi/1238acd4584a4fdf857b26fef2d160ba to your computer and use it in GitHub Desktop.
Memoized function for better performance
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
/** | |
* @version 2 | |
* @description memoized function for better performance | |
* @param {function} func | |
* @returns {function} func | |
*/ | |
function memoize(func){ | |
const cache = new Map(); | |
return (...args)=>{ | |
const key = args.join(''); | |
if(cache.has(key)) return cache.get(key); | |
result = func(...args); | |
cache.set(key, result); | |
return result; | |
} | |
} | |
/** | |
* @version 1 | |
* @description memoized function for better performance | |
* @param {function} func | |
* @returns {function} func | |
*/ | |
function memoize(func) { | |
var cache = {}; | |
return function() { | |
var id = JSON.stringify(arguments); | |
if (cache[id] === undefined) | |
cache[id] = func.apply(this, arguments); | |
return cache[id]; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment