Memoization is a function optimization technique used to avoid remaking calculations in subsequent function calls. The classic example, which we’ll demonstrate here, is the factorial function. 5! = 5 * 4 * 3 * 2 * 1… factorials are recursive in nature if we give it some thought. 5! = 5 * 4! and 4! = 4 * 3! and so on. By recognizing this pattern, we can also recognize that if we calculate 5! and save the results, then we should not have to recalculate it when we do 7!. Instead of calculating 7! by 7 * 6 * 5 * 4 * 3 * 2 * 1, we’ll calculate it by 7 * 6 * 5!.
We’ll first examine the naive approach and then the memoization method. All in Javascript, and all with code samples…
[Read More]