Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Advanced JavaScript

You're reading from   Advanced JavaScript Speed up web development with the powerful features and benefits of JavaScript

Arrow left icon
Product type Paperback
Published in Jan 2019
Publisher
ISBN-13 9781789800104
Length 330 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Zachary Shute Zachary Shute
Author Profile Icon Zachary Shute
Zachary Shute
Arrow right icon
View More author details
Toc

Chapter 1: Introducing ECMAScript 6


Activity 1 – Implementing Generators

You have been tasked with building a simple app that generates numbers in the Fibonacci sequence upon request. The app generates the next number in the sequence for each request and resets the sequence it is given an input. Use a generator to generate the Fibonacci sequence. If a value is passed into the generator, reset the sequence. You may start the Fibonacci sequence at n=1 for simplicity.

To highlight how the generators can be used to build iterative datasets, follow these steps:

  1. Look up the Fibonacci sequence and understand how the next value is calculated.

  2. Create a generator for the Fibonacci sequence.

  3. Inside the generator, set up the default values for current and next (0, 1) using variables n2 and n1.

  4. Create an infinite while loop.

  5. Inside the while loop, use the yield keyword to provide the current value in the sequence and save the return value of the yield statement into a variable called input.

  6. If input contains a value, reset the variables n2 and n1 to their starting values.

  7. Inside the while loop, calculate the new next value from current + next and save it into the variable next.

  8. Otherwise update n2 to contain the value from n1 (the next value) and set n1 to the next value that we calculated at the top of the while loop.

Code:

index.js
function* fibonacci () {
 let n2 = 0;x
 let n1 = 1;

 while ( true ) {
   let input = yield n2;
   if ( input ) {
     n1 = 1;
     n2 = 0;
   } else {
     let next = n1 + n2;
     [ n1, n2 ] = [ next, n1 ];
   }
 }
}
let gen = fibonacci();

Snippet 1.87: Implementing a generator

Outcome:

Figure 1.19: Fibonacci sequence with a generator

You have successfully demonstrated how generators can be used to build an iterative data set based on the Fibonacci sequence.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime