Advertisement
728x90
Memoization is a functional programming technique which attempts to increase a function’s performance by caching its previously computed results. Each time a memoized function is called, its parameters are used to index the cache. If the data is present, then it can be returned, without executing the entire function. Otherwise the function is executed and then the result is added to the cache.
Let's take an example of adding function with memoization,
javascript
1const memoizeAddition = () => {
2
3let cache = {};
4
5return (value) => {
6 if (value in cache) {
7 console.log("Fetching from cache");
8 return cache[value]; // Here, cache.value cannot be used as property name starts with the number which is not a valid JavaScript identifier. Hence, can only be accessed using the square bracket notation.
9 } else {
10 console.log("Calculating result");
11 let result = value + 20;
12 cache[value] = result;
13 return result;
14 }
15};
16};
17// returned function from memoizeAddition
18
19const addition = memoizeAddition();
20
21console.log(addition(20)); //output: 40 calculated
22
23console.log(addition(20)); //output: 40 cachedAdvertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 27
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
25of476