Optimizing JavaScript Functions with Memoization

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will be exploring the concept of memoization in JavaScript. Memoization is a technique used to optimize function performance by caching the results of expensive function calls and returning the cached result when the same inputs occur again. Through this lab, we will learn how to implement memoization in JavaScript using the Map object.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/ToolsandEnvironmentGroup(["`Tools and Environment`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/functions("`Functions`") javascript/BasicConceptsGroup -.-> javascript/obj_manip("`Object Manipulation`") javascript/AdvancedConceptsGroup -.-> javascript/closures("`Closures`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/ToolsandEnvironmentGroup -.-> javascript/debugging("`Debugging`") subgraph Lab Skills javascript/variables -.-> lab-28494{{"`Optimizing JavaScript Functions with Memoization`"}} javascript/data_types -.-> lab-28494{{"`Optimizing JavaScript Functions with Memoization`"}} javascript/arith_ops -.-> lab-28494{{"`Optimizing JavaScript Functions with Memoization`"}} javascript/comp_ops -.-> lab-28494{{"`Optimizing JavaScript Functions with Memoization`"}} javascript/functions -.-> lab-28494{{"`Optimizing JavaScript Functions with Memoization`"}} javascript/obj_manip -.-> lab-28494{{"`Optimizing JavaScript Functions with Memoization`"}} javascript/closures -.-> lab-28494{{"`Optimizing JavaScript Functions with Memoization`"}} javascript/higher_funcs -.-> lab-28494{{"`Optimizing JavaScript Functions with Memoization`"}} javascript/debugging -.-> lab-28494{{"`Optimizing JavaScript Functions with Memoization`"}} end

Memoize Function

To start coding, open the Terminal/SSH and type node. This function returns the memoized (cached) function. Here are the steps to use this function:

  1. Instantiate a new Map object to create an empty cache.
  2. Return a function that takes a single argument which will be supplied to the memoized function. Before executing the function, check if the output for that specific input value is already cached. If it is, return the cached output; otherwise, store and return it.
  3. Use the function keyword to allow the memoized function to have its this context changed if necessary.
  4. Set the cache as a property on the returned function to allow access to it.

Here's the code that implements the memoize function:

const memoize = (fn) => {
  const cache = new Map();
  const cached = function (val) {
    return cache.has(val)
      ? cache.get(val)
      : cache.set(val, fn.call(this, val)) && cache.get(val);
  };
  cached.cache = cache;
  return cached;
};

To see how this function works, you can use it with the anagrams function. Here's an example:

const anagramsCached = memoize(anagrams);
anagramsCached("javascript"); // takes a long time
anagramsCached("javascript"); // returns virtually instantly since it's cached
console.log(anagramsCached.cache); // The cached anagrams map

Summary

Congratulations! You have completed the Memoize Function lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like