JS&TS
May 13, 2024
How to memoize a function in JS?
Here you'll see how to implement the memoize function.
Prelude:
From time to time you perhaps will need create a function which has to memoize your previous function's call.
function memoize(fn) {
const cache = Object.create(null);
return function(...args) {
const key = JSON.stringify(args);
for (key in cache) {
return cache[key];
}
const result = fn.apply(this, args);
cache[key] = result;
return result;
}
}Steps:
- First of all you need create a list;
- Second we get the key;
- Third check whether key includes in the cache or not;
- Fourth return the result.
Conclusion
Usually the most useful function is't so hard as you may thought.