A Practical Guide to Algorithms with JavaScript

Recursive Factorial & Memoize Solution

A Practical Guide to Algorithms with JavaScript

Check out a free preview of the full A Practical Guide to Algorithms with JavaScript course

The "Recursive Factorial & Memoize Solution" Lesson is part of the full, A Practical Guide to Algorithms with JavaScript course featured in this preview video. Here's what you'd learn in this lesson:

Bianca walks through the solution to Recursive Factorial & Memoize Exercise.

Preview
Close

Transcript from the "Recursive Factorial & Memoize Solution" Lesson

[00:00:00]
>> Bianca Gandolfo: So we're just gonna hop into the solution here. We're gonna call our factorial with the value five. However, if we check out what factorial is, factorial is wrapped, it's actually being called with another function. So first, we're passing this function. Right, which is just a typical factorial.

[00:00:23]
We're doing our work here. Here's our base case.
>> Bianca Gandolfo: But we're passing it to this function memoize. So let's check out what's happening in memoize. So memoize expects a function. And it's caching. This looks familiar, right, from our previous examples? So we're going to return, we're going to return this function.

[00:00:48]
And we just, we're just gonna call our factorial there. So when we calculate the factorial of five, what happens is, we're gonna jump in to this function here. So this is gonna be five, and it's five. So we're gonna check if it's in the cache. it's not in the cache yet, otherwise, we're gonna calculate it.

[00:01:12]
So we're gonna do Fibonacci of five, I'm sorry, factorial of five, and then we're gonna [LAUGH] cache that. And we're gonna return that results. All right, great, so let's check this one out. So we're gonna do factorial, actually, sorry, we did not in there, I'm skipping many steps, which is we are gonna call this call back, and then we are going to do some work here, and we're gonna recursively call our factorial, and do our recursive steps.

[00:01:55]
>> Bianca Gandolfo: Cool, and this actually isn't doing this, I just realized. It is doing something a little bit different. But, if we reference this, it's going to be cached, just like in our other example, and we're not needing to calculate it everytime. The other thing that we can do, is we can cache this line, so that we have a check and to see if this has already been calculated and cached, but this isn't what the solution is doing.

[00:02:24]
But that's another way of memoizing this.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now