Memoization

It is a process of storing the reoccurring calls to a function and use them if they get called again. Used for runtime optimization. Applying Memoization on Fibonacci series recursive solution.

It is a process of storing the reoccurring calls to a function and use them if they get called again. Used for runtime optimization.

Applying Memoization on Fibonacci series recursive solution.

function memoize(fn)
{
	//stores all the calls to our function here we mean fib function.
	const cache ={};
    
	//...args basically means arguments of our function 
	//i mean the function that is being sent to the memoize 
	//can contain n number of arguments so this takes care of it.
	//It takes all the arguments and assign them as an array 
	//to this variable called args
    return function(...args)
    {
		if(cache[args])
		{
        	return cache[args];
        }
        
		//when ever we call a function with an array of arguments
		//then we have to use the Apply helper
        const result = fn.apply(this, args);
        cache[args] = result;
        return result;
    }
}

function fib(n) {
	if(n<2)
	{
		return n;
	}

	return fib(n-1) + fib(n-2);
}

	fib = memoize(fib);

Leave a Reply

Your email address will not be published. Required fields are marked *