DEV Community

Daniel Zaltsman
Daniel Zaltsman

Posted on

Fizzbuzz

Fizzbuzz is a test that was devised to filter out 99.5% of candidates who are very weak programmers. It also shows what style of programming people use, as this question can be handled a many number of ways.

Here is the problem: Write a program that outputs the string representation of numbers from 1 to n. But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Before I tackled this question, I thought more about scalability than just immediately answering the problem. I had thought if I hashed the keys and the values, I would be able to add more keys if it was needed. Here is my original solution:

var fizzBuzz = function(n) {


    let result = []
    let fizzObject = {
        3: 'Fizz',
        5: 'Buzz',
        // 7: 'Jazz'
    } 
    let numArray = [3,5]

    for(let i = 1; i < n + 1; i++){
        let result_str = ''
        numArray.map((key) => {
            if(i % key === 0){
               result_str += fizzObject[key]
               }            
        })        
        if(!result_str){
            result_str = i.toString()
        }
        result.push(result_str)
    }    
    return result
};

Notice the commented out "7" key and value "Jazz". If I wanted to extend this solution, I can do it easily! However, it is very slow. So I tested out my other solution to see how fast, albeit naive, it is:

var fizzBuzz = function(n) {
    let result = [];
    for (i = 1; i <= n; i++) {
        if (i % 3 == 0 && i % 5 == 0) result.push("FizzBuzz");
        else if (i % 3 == 0) result.push("Fizz");
        else if (i % 5 == 0) result.push("Buzz");
        else result.push(i + "");
    }
    return result;
};

This solution is much faster, but it may become messy depending on how many lines of code you need to add to account for new modifications.

Top comments (0)