Memoization in JavaScript
How to Implementing Memoization in JavaScript
Memoization is an optimization technique that can be used to reduce time-consuming calculations by saving previous input to something called cache and returning the result from it.
In Simple word, if any value is coming back again and again. So at this point you can save this value as cache and use it if you make this call.
Supposed,
This is a small function, so it won't take more time to implement. But consider the larger function, and this execution time is 1000ms, so will you call again and again?function add(value) {let addition = 0;for (let i = 0; i <= value; i++) {addition += i;}return addition;}const result = add(5);console.log(result); // result is 15
obviously no❗
You need to save this value to a specific location and call it.
like,
What is happened?function add(value) {let addition = 0;for (let i = 0; i <= value; i++) {addition += i;}return addition;}function memorization(fun) {let cache = {};return function (...args) {const n = args[0];if (n in cache) {console.log('catch')return cache[n];} else {console.log('first time')const res = fun(n);cache[n] = res;return res;}}}const output = memorization(add);output(5) // first timeconsole.log(output(5)) //cache
we pass the add function inside memorization function and access as an argument, remember callback function. and we returning another function so it forms a closure and check if value is already present then return saved value else return new value and save it in cache.
we call memorization and pass add() function and stored in output, also memorization return another function so we pass the arg. and call it.
first time cache 15
Post a Comment