You are currently viewing JavaScript Coding Interview Series Part 1: Implementing the Memoize Function

JavaScript Coding Interview Series Part 1: Implementing the Memoize Function

The Memoize function is one of the most asked interview questions for the Javascript FullStack developer role. If you know Dynamic Programming (DP), then it will be easy for you.

I have researched and prepared a list of javascript coding questions asked in Frontend/Fullstack role.

This is the first question of the series of 30 important coding problems.

Why Memoize?

Memoization is used to speed up your code by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

It helps improve performance by reducing redundant processing. For example, recursive functions like calculating Fibonacci numbers or solving factorials can benefit significantly from memoization.

Implement Memoize function in Javascript

Memoization can be implemented in Javascript using a closure. In an interview, if you are asked about a closure’s usage or application example, you can mention Memorization.

Problem statement

Implement a function in Javascript that stores the result for the given input and returns the cached value for the same input on subsequent function calls.

e.g

function expensiveFunction(args) {}

const memoized = memoize(expensiveFunction);

// first calling would be slow but next call should be very fast.

so we need to build this memoize function.

Implementation

const memoize = function(fn) {
  const res = {};
  return (...args) => {
    const context = this;
    const key = args.join("");

    res[key] = res[key] || fn.apply(context, args);

    return res[key];
  }
}

function factorial(n) {
  if (n === 0 || n === 1) {
    return 1;
  }
  return factorial(n - 1) * n;
}

const memoizedFactorial = memoize(factorial);
let a = memoizedFactorial(160); // slow
console.log(a); // 4.714723635992059e+284

let b = memoizedFactorial(160); // faster
console.log(b); // 4.714723635992059e+284

We can see on subsequent call, the function is returning the value from cache if its call for the same input.

I hope you liked the article, if you do please share among your friends. This site is run by the ads if you like the article continuely being published please help us by disabling your ads from chrome extensions for this site.

You can try to implement here – PlayCode

To read other popular javascript articles checkout this –

Complete Javascript Playlist – Javascript Collection 

Thanka a lot! I’ll publish the next part soon…