Fizz-Buzz Test with Sass


Ah yes, the ol' Fizz-Buzz test. If you haven't done it before, it's a small activity designed to reveal a programmer's basic knowledge of a language. It's simple enough that you may even be asked to do it in an interview:

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

As a front-end developer it was easy enough to reach for the JavaScript pencil and get things wrapped up in a neat and tidy bow relatively quickly. I wasn't satisfied, though! Challenging yourself is a big part of learning new skills. I allowed my mind to wander: can I do this in Sass? Can I do this in Sass with a single DOM element?

$content: "";

@for $i from 1 through 100 {
  @if $i % 15 == 0 {
    $content: append($content," FizzBuzz\a");
  } @elseif $i % 3 == 0 {
    $content: append($content," Fizz\a");
  } @elseif $i % 5 == 0 {
    $content: append($content," Buzz\a");
  } @else {
    $content: append($content," #{$i}\a");
  }

  @if $i == 100 {
    .fizziest-of-buzzes:before {
      content: $content;
      white-space: pre;
    }
  }
}

The outcome of the example above may not seem particularly useful but the tools that got us there certainly are. Sass can be a programming language when you need it to be. You can write mixins and functions that solve a significant amount of repetition. Embrace the power of Sass!

Checkout the Codepen to play around with it. I recommend implementing Fizz-Buzz in your language of choice and then trying it in another one.

This was originally posted on code.graygilmore.com and has been modified for the Stembolt blog.