TypeScript Fundamentals TypeScript Fundamentals

Challenge 6: Fibonacci Generator

Check out a free preview of the full TypeScript Fundamentals course:
The "Challenge 6: Fibonacci Generator" Lesson is part of the full, TypeScript Fundamentals course featured in this preview video. Here's what you'd learn in this lesson:

In this challenge, students build a generator function that returns an iterator, which emits the numbers of the Fibonacci sequence.

Get Unlimited Access Now

Transcript from the "Challenge 6: Fibonacci Generator" Lesson

[00:00:00]
>> Mike North: This should be a really easy exercise because the solution's already in the slide. But I do wanna give you an opportunity to try your hand at working with iterators yourselves. So we're going to build a Fibonacci Generator. Now we've already seen what that looks like, but this is a good ice-breaker exercise for the day.

[00:00:23] So what I wanna do is take 15 minutes to just kind of wrap your head around this. Particularly if you're still a little bit hung up on the pausing execution and if this still feels like a really puzzling concept to you. I would advise that you do most of this exercise inside Chrome devtools with a snippet, like I was just doing.

[00:00:50] So if you go to the sources tab, on the left side one of the little sidebar things says snippets. You can create a new snippet. Do your code in there. The benefit is you can set breakpoints. You're basically working within a debuggable environment already. And so that'll help you step through things.

[00:01:08] That being said, we have an exercise with tests that assert that your generator works properly. And you're gonna run npm test fib. Now I'm gonna give you a suggested implementation here because this is not a big tech company interview. We're not trying to quiz people and figure out if they know the easy special way to implement a Fibonacci algorithm.

[00:01:34] What I do want you to see is if we look at how things would look if we were tracking two numbers ago, one number ago in order to calculate the next value. Because that's what the Fibonacci sequence is, right? The sum of the two previous values is the next value.

[00:01:50] If you look, you see diagonal lines from the bottom left to the top right. Those are all the same, right? So the diagonal lines, if we start, you see 1, 1, 1, 2, 2, 2, 3, 3, 3, 5, 5. And it would continue like that. So sometimes people get stuck on this starting condition, where you pick the right initial values for those variables, such that you get those first two ones.

[00:02:16] And this should give you some help as to figuring out what those should be. I don't want people to get stuck on the Fibonacciness here. This is about the generator function.