FizzBuzz: Writing and Testing the Classic Problem in JavaScript
Published: 2023-09-11 20:10:47

## Introduction

In this tutorial, we will walk through solving the classic FizzBuzz problem in JavaScript. The code and testing procedures are part of my "EssentialAlgos" project available on [GitHub](https://github.com/willshepp28/EssentialAlgos).

If you'd like to connect with me professionally, find my LinkedIn profile [here](https://www.linkedin.com/in/will-sheppard-81a184145/) and my GitHub profile [here](https://github.com/willshepp28).

## What is FizzBuzz?

FizzBuzz is a programming challenge often used in coding interviews. The task is to print numbers from 1 to `n`, replacing multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both 3 and 5 with "FizzBuzz".

## The Core FizzBuzz Function

Let's dive right into the code. The `fizzBuzz` function in JavaScript is as follows:


```javascript
// fizzBuzzVersion2
let fizzBuzz = (int) => {
    let arr = [];

    for(let index = 1; index <= int; index++){
        let value = '';

        if(index % 3 === 0){
            value += "Fizz";
        }

        if(index % 5 === 0){
            value += "Buzz";
        }

        if(!value){
            value += `${index}`;
        }

        arr.push(value);
    }

    return arr;
}
```

To be totally transparent this was the original version i came up with before the refactored version above.

```javascript
// originalFizzBuzz
let fizzBuzz = (int) => {
    let arr = [];
    
    for(let index = 1; index <= int; index++) {
      if(index % 3 === 0 && index % 5 !== 0) {
        arr.push("Fizz");
        continue;
       }

      if(index % 5 === 0 && index % 3 !== 0){
        arr.push("Buzz")
        continue;
      } 

      if(index % 5 === 0 && index % 3 === 0) {
          arr.push("FizzBuzz");
          continue;
      }

      arr.push(`${index}`)
    }

    return arr;
}
```


This function takes an integer `int` and returns an array containing the FizzBuzz sequence.

## Testing FizzBuzz with Jest

Testing is crucial for validating the correctness of your code. I have written Jest tests for this function. I've written test for both version that i've created for fizzBuzz

```javascript
const originalFizzBuzz = require("./fizzbuzz");
const fizzBuzzVersion2 = require("./fizzbuzz.v2/fizzbuzz.v2");

const checkReturnsEmptyArray = (func) => {
    let arr = func();
    expect(arr).toStrictEqual([]);
};

describe('FizzBuzz Tests', () => {
    describe('Empty Array Tests', () => {
        test.each([
            [originalFizzBuzz, 'Returns an empty array when given no values'],
            [fizzBuzzVersion2, 'Returns an empty array when given no values']
        ])('%s', (func, description) => {
            checkReturnsEmptyArray(func);
        });
    })

    describe('Output for Input 3', () => {
        test('Original version should return ["1", "2", "Fizz"] when given 3', () => {
            const arr = originalFizzBuzz(3);
            expect(arr).toStrictEqual(["1", "2", "Fizz"]);
        });
    
        test('Version 2 should return ["1", "2", "Fizz"] when given 3 for v2', () => {
            const arr = fizzBuzzVersion2(3);
            expect(arr).toStrictEqual(["1", "2", "Fizz"]);
        });
    });

    describe('Output for Input 15', () => {
        test('Original version should return the expected FizzBuzz sequence up to 15', () => {
            const arr = originalFizzBuzz(15);
            expect(arr).toStrictEqual(["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]);
        });

        test('Version 2 should return the expected FizzBuzz sequence up to 15', () => {
            const arr = fizzBuzzVersion2(15);
            expect(arr).toStrictEqual(["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]);
        });
    })

});
```

This test ensures that when the function is provided an input, it returns the right output.

## LeetCode Submission and GitHub Repository

You can find my FizzBuzz submission on [LeetCode](https://leetcode.com/problems/fizz-buzz/submissions/). The complete code and tests are available in my GitHub repository: [EssentialAlgos](https://github.com/willshepp28/EssentialAlgos).

## Conclusion

We have successfully tackled the FizzBuzz problem and validated its correctness through Jest testing. This exercise is a foundational problem but provides a valuable practice platform for budding coders and seasoned developers alike.

Feel free to connect with me for any questions or discussions on algorithms, coding, or potential opportunities:
- [LinkedIn](https://www.linkedin.com/in/will-sheppard-81a184145/)
- [GitHub](https://github.com/willshepp28)

Happy coding! 🚀