Khandagale-Saurabh / Pesto-

0 stars 0 forks source link

lodash memorize | Imp | Before interview #4

Open Khandagale-Saurabh opened 2 years ago

Khandagale-Saurabh commented 2 years ago

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;

        console.log('Argument added '+cache);
        for(let i in cache){
            console.log(i);
        }
        return result;
     }
}

} const check=createFast(fib) //userdefine console.log('#################');

time(()=>check(35)) time(()=>check(35)) time(()=>check(35)) time(()=>check(39)) time(()=>check(39))

Khandagale-Saurabh commented 2 years ago

image

Khandagale-Saurabh commented 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