Memoized Factorial Function in Javascript

Get factorial of a given number using memoization techniques.

Previously we have seen how memoization can be used in a reusable function to get all the advantages of memoization, without the complexity.

Today, let us see one more practical example - get factorial of a given number.

First, create a function to calculate factorial.

let factorial = function(n) {
  return n <= 1 ? 1 : n * factorial(n - 1);
};

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

Then, wrap the factorial function in memoThis.

let memoThis = function(func) {
  const cache = {};
  return (...args) => {
    const key = JSON.stringify(args);
    return key in cache ? cache[key] : (cache[key] = func(...args));
  };
};

let factorial = memoThis(function(n) {
  return n <= 1 ? 1 : n * factorial(n - 1);
});

console.log(factorial(5));
// 120
comments powered by Disqus