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.
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:
- Instantiate a new
Mapobject to create an empty cache. - 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.
- Use the
functionkeyword to allow the memoized function to have itsthiscontext changed if necessary. - Set the
cacheas 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.