FizzBuzz in JavaScript using Generators

FizzBuzz

A common programming test for job candidates is FizzBuzz. I will show how to solve the FizzBuzz problem using generators in JavaScript. There are some variations on this test but the basics are to print out a sequence of numbers with the following restrictions:

  • if the number is divisble by 3 then print out "Fizz"
  • if the number is divisible by 5 then print out "Buzz"
  • if the number is divisible by 3 and 5 then print out "FizzBuzz"

Example output from a FizzBuzz program is shown below:

1
2
Fizz
4
Buzz
...

What are Generators?

Before jumping into the solution let's delve into what JavaScript generators are. Generators are a new feature in EcmaScript 6 that allow you to return an arbitrary set of values from a function and suspend the function in between returning a value.

For example, a generator might return all the numbers from 1 to 100 or the numbers in the Fibonnaci sequence. Generators act synchronously. It's a common misconception that they act asynchronously. The magic sauce in generators is the yield keyword that works very similarly to the yield keyword in C#.

The generators in ES6 are perfect for solving the FizzBuzz problem elegantly.

function *fizzBuzz() {
    
    for( var i=1; i< 100; i++) {
        var output = "";
    	if( i % 3 == 0 )
			output += "Fizz";
        
        if(i % 5 == 0 )
        	output += "Buzz";
            
        if(!output)
        	output = i.toString();
        
        yield output;
    }
}

var gen = fizzBuzz();
console.log(gen.next().value); // prints 1
console.log(gen.next().value); // prints 2
console.log(gen.next().value); // prints "Fizz"
console.log(gen.next().value); // prints 4

It's awesome how easily generators can be iterated over in loops.

for (n of fizzBuzz()) {
    console.log(n);
}

When Can I Use Generators?

Today!!! There are two ways to run JavaScript code that has generators. Get a version of Node that is at least version 0.11 or higher (keep in mind 0.12 will be the first stable release of Node with generators). When running Node use the --harmony flag on the command line to enable ES6 features.

In the Chrome browser you can use generators if you enable the Enable Experimental JavaScript flag.

// in Chrome type the following command in the browser bar
chrome://flags/#enable-javascript-harmony

References