Brian walks through the solution to exercise 1. He also demonstrates how to include unit testing libraries in CodePen.
Okay, let's work through this together, so here we're gonna put our code. I have my notes here. I'm gonna make a function called factorial, and it's gonna take an n, oh, another interesting thing to note about CodePen, is if you see this red exclamation point down here, it means that it's not compiling. So if you click on that, it's gonna tell you, it's gonna start yelling at you, Unexpected identifier.
First line of our recursion, what's the first thing we're gonna do? Base case, right? If n is less than two, then we're going to return one. Pretty simple, okay? And now, what is the factorial? Well, it's n times factorial of n minus one.
That's it. And if you look down here, notice that our test is now passing. So, again, just to demonstrate here, like it's factorial, like if you think about it, right? It's whatever the number is times whatever the factorial of the number minus one, right? And that's literally what we're expressing into the code, right? It's n times factorial of n minus 1. So that's something that can really help you, is just to like, reason aloud of what's happening.
Another, this is helpful for me and it's confusing for other people, so I'm going to state it and if it makes you more confused, just throw it away. (laughs) You can kind of think of the body of the function of a recursive function like the inner part of a loop. That's a very leaky abstraction so don't go too far with that. Just think of like, that's the code that gets run over and over and over again. Just like if you do a four loop, whatever the code's in the middle of the four loop that's what gets run over and over and over again. This is the same general concept. This is the code that's gonna get run a bunch of times.
Maybe that helps you, maybe it doesn't. Any questions? All right, so let's close that. Leave this page, leave that page. And again, all the answers are up here, so if you're struggling or you wanna go back later and look at it, all the answers that I am putting up here, they have them right here as well. I think I fixed all of them too. One of them was wrong, yeah, right there.
Note: This course was created by Frontend Masters. It was originally released on 07/12/2016. We're pleased to host this training in our library.
- Big O
- Sort: Bubble, insertion, and merge,
- Median values
- Set, map, stack, and queue
- Array lists and linked lists
- Binary search tree
- AVL tree
- Single rotation and double rotation
- Hash table
- Functional programming
- Map, reduce, and filter