Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8688

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T03:28:09+00:00 2024-11-28T03:28:09+00:00

JavaScript Interviews: Implement Memoization in JavaScript

  • 60k

What is this series about?

Hello all! Welcome to the JavaScript interview questions series. In each post of this series, I will talk about the questions (specific to JavaScript) I faced in my recent interviews. This series will be helpful for you if you are preparing for JavaScript interviews or just started to deep dive into JavaScript and want to test your knowledge.

Post 2: Implement Memoization in JavaScript

Imagine you do not have a memory inside your brain. And someone asks you a question like, “What is 14353 * 34789?”. You do the calculation and give the answer. Because you do not have any memory, this question and its answer have been wiped out of your mind. Now again if someone asks you the same question, you will again do the calculation and give the answer. Doing this calculation is tedious and it used some of your energy. Isn't this frustrating?

Now let us come to the real world. You have the memory. Someone asks “What is 14353 * 34789?”. You do the calculation and give the answer. Now, this question and answer are stored inside your short-term memory. If again in few seconds, you are asked the same question, you will directly access the memory and give the answer without any calculation.

This technique is known as Memoization. In computer science also, this technique is used to avoid heavy calculations. Now enough of imagination. Let us dive into the real interview question. 👨‍💻👨‍💻

Problem Statement

Write a function memoize which will receive a function and return its memoized version. When the memoized function is called with the same parameters, again and again, it will just log the value with a message “Did not perform calculations. Here is your answer: “. If those parameters have never been passed, it will just print the answer.

function memoize(fn) {   // Write your code here }  function multiply(num1, num2) {   return num1 * num2; }  const memoizedMultiply = memoize(multiply);  memoizedMultiply(9, 10); // Expected Output:  90  memoizedMultiply(9, 10); // Expected Output:  Did not perform calculations. Here is your answer: 90  memoizedMultiply(8, 10); // Expected Output:  80 
Enter fullscreen mode Exit fullscreen mode

Before diving into the solution, I highly suggest that you try to solve this problem on your own. Here is a hint: Think Closures.

Solution

As mentioned in the previous post, I always start with the basic stuff being asked in the question. The problem statement tells us that we have to return a function that will call the function that we want to memoize and print the result. Let us write that part first.

function memoize(fn) {   return function(...args) {     const result = fn(...args);     console.log(result);   } } 
Enter fullscreen mode Exit fullscreen mode

Great. The next thing problem asks us to memoize the result if we pass the same parameters to the memoized function. This seems like a good opportunity to use Closures. If you are unfamiliar with closures, please read about them here. With the help of the closure, our returned function will have to the variables declared in its parent scope. Let us add the Closure now.

function memoize(fn) {   var argumentsMap = {};   return function(...args) {     const result = fn(...args);     console.log(result);   } } 
Enter fullscreen mode Exit fullscreen mode

The idea we are trying to follow here is:

  1. When the memoized function is called, we will store the arguments in the argumentsMap as keys and store the result for that argument as its value.
  2. If the function is called for the same parameters, we will check if argumentsMap has the parameters as key. If yes, will directly get the value and not perform any calculations.

The obvious question here is that how will we store the arguments as a key in argumentsMap? For that, I have chosen an approach where I will apply JSON.stringify on arguments and then store them as keys. You can come with a different approach for this which you might think is better. I Would love to see what you think about how this can be done. Please share your approaches in the comments.

With that sorted out, the rest of the code is very simple. We will just add few checks and print the results. The final version of my answer looks like this:

function memoize(fn) {   var argumentsMap = {};   return function(...args) {     const argumentKey = JSON.stringify(args);     if (argumentsMap[argumentKey]) {       console.log('Did not perform calculations. Here is your answer: ', argumentsMap[argumentKey]);       return;     }     const result = fn(...args);     argumentsMap[argumentKey] = result;     console.log(result);   } } 
Enter fullscreen mode Exit fullscreen mode

Conclusion

Yay!! This looks like a working solution for now. I would love to know what approaches you can come up with for this problem. Do post your suggestions in the comments. And for more interesting questions like this, keep following this series. Until then, Happy Coding!!

careerjavascriptprogrammingwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.