A programming technique called memory seeks to improve function performance by caching previously computed results. The parameters of a memoized function are used each time it is invoked to index the cache. Without running the complete code, the data can be returned if it is present. If not, the function is called, and the output is then cached.

Dynamic programming uses a particular kind of caching called memorization. By using caching, we can speed up our programs and store some data in an easily accessible location for future use. When we call immediately, it returns the others immediately while storing the prior result.

Additionally, when the same set of arguments yields the same output and performant online applications, memoization is a cache optimization approach.

Fibonacci sequence

Without having to memorization it, let's develop a function that computes the Fibonacci sequence.

Each value in the Fibonacci sequence is a list of numbers where the sum of the two values before it.

// fibonacci without memoization
const fib = (num) => {
    if (num < 2) {
        return 1
    } else if (!num || typeof num !== 'number') {
        return 'value must be a number!'
    }
    return fib(num - 1) + fib(num - 2)
}

console.log(fib(10))

As you can see from the code above, we didn't cache how our function was used. With caching, the process will go much more quickly and in less time.

// fibonacci sequence with memoization to run the function fib()
const fib = (num) => {
    let cache = {}; // set cache
    // if exists in cache return from cache
    if (cache[num] !== undefined) {
        console.log(`${num} is cached!`);
        return cache[num];
    }
    // if not in cache perform operation
    cache[num] = num < 2 ? 1 : fib(num - 1) + fib(num - 2);
    return cache[num];
}
const result = fib(5)
console.log(result) // 8

We produced a cache object from the aforementioned code piece, which the fib() utilises to store its output value. Every time the function is called, the first thing it does is see if the input num has already been saved in the cache object. If so, the application immediately returns the stored value.

Exercise

Let's use the factorial() function's cache execution to get the factorial of a given number.

// factorial of a number with memoization (cache execution)
const factorial = (num) => {
  let cache = {}; // set cache
  // if cache already exists, return cache
  if (cache[num] !== undefined) {
    console.log(`${num} is cached!`);
    return cache[num];
    // edge case validation for not a number
  } else if(!num || typeof num != 'number') {
      return `value must be a number`
    }
  cache[num] = 
    num === 0 
    ? 1 : num === 2 ? 2 
    : num * factorial(num - 1); // condition ternary operator, same with if/else statement
  return cache[num];
};

console.log(factorial(5)); // 120


Recommended Posts

View All

Difference Between == and === in JavaScript


Learn the Difference Between == and === in JavaScript. Discover how each operator compares values and data types, and when to use them in code.

How do you decode or encode a URL in JavaScript?


Learn how to encode and decode URLs in JavaScript with this comprehensive guide. Avoid common mistakes and ensure data security. Read more now.

JavaScript Template Literals Explained


JavaScript template literals are one of JavaScript's most powerful capabilities. They enable us to generate dynamic strings without the need for conca...

Global Variables in JavaScript Explained


Global variables are defined outside of functions or alongside window objects for use throughout the program

The Difference Between Slice and Splice in JavaScript


Discover the nuances between slice() and splice() in JavaScript. Learn how to use these methods to manipulate arrays with ease. Read on to find out mo...