Open Khandagale-Saurabh opened 2 years ago
const memoizAddition = () => { let cache = {}; return (value) => { if (value in cache) { console.log("Fetching from cache"); return cache[value]; // Here, cache.value cannot be used as property name starts with the number which is not a valid JavaScript identifier. Hence, can only be accessed using the square bracket notation. } else { console.log("Calculating result"); let result = value + 20; cache[value] = result; return result; } }; }; // returned function from memoizAddition const addition = memoizAddition(); console.log(addition(20)); //output: 40 calculated console.log(addition(20)); //output: 40 cached
https://www.youtube.com/watch?v=dO9LQsIpavM 1] craete cache
2] check if argument exists or not if(yes)=>fetch from their else add in cache cache can be map or any suitable data structure or object [{} is object bolte hai]
let mem=require('lodash.memoize') function fib(n) { if(n<2) {return n; }
return fib(n-1)+fib(n-2); }
function time(fnn) { console.time(); fnn(); console.timeEnd(); }
time(()=>fib(35)) time(()=>fib(35)) time(()=>fib(35)) time(()=>fib(39)) time(()=>fib(39))
console.log('============')
const Fm=mem(fib) // system define time(()=>Fm(35)) time(()=>Fm(35)) time(()=>Fm(35)) time(()=>Fm(39)) time(()=>Fm(39))
const createFast=(fn)=>{ const cache={}; return function(...args){ if(cache[args]) { console.log('Argument Already Prest '); for(let i in cache){ console.log(i); } return cache[args] } const result =fn(...args) { cache[args]=result;
} const check=createFast(fib) //userdefine console.log('#################');
time(()=>check(35)) time(()=>check(35)) time(()=>check(35)) time(()=>check(39)) time(()=>check(39))