Skip to content

Instantly share code, notes, and snippets.

@behnammodi
Last active December 5, 2020 23:39
Show Gist options
  • Save behnammodi/1238acd4584a4fdf857b26fef2d160ba to your computer and use it in GitHub Desktop.
Save behnammodi/1238acd4584a4fdf857b26fef2d160ba to your computer and use it in GitHub Desktop.
Memoized function for better performance
/**
* @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