## Memoized Factorial Function in Javascript

·   ·  ☕ 1 min read

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.

 1 2 3 4 5 6  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.

  1 2 3 4 5 6 7 8 9 10 11 12 13 14  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 
Stay in touch!
Share on

WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things