HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

The Scripted FizzBuzz Kata

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
katathefizzbuzzscripted

Problem

I run a coding dojo at work. for one session I'm to showing that you can use a kata to get into a new language.

I'm using the FizzBuzz Kata to show JavaScript (and F#) because it is short. The problem is my JavaScript knowledge is only slightly above the copy -> paste -> fiddle level.

Thus, I would like to see better ways of doing this (using qunit):

var fizzBuzzer = (function () {
    var For = function (number) {
        var isBuzz = number % 5 === 0;
        var isFizz = number % 3 === 0;

        if ((isFizz) && (isBuzz)) {return "FizzBuzz";}
        if (isBuzz ) {return "Buzz";}
        if (isFizz ) {return "Fizz";}

        return number;
    };

    return { For: For };
})();

test("not a multiple of 5 or 3 returns number", function () {
    equal(fizzBuzzer.For(1), 1);
    equal(fizzBuzzer.For(2), 2);
});

test("multiple of 3 returns Fizz", function () {
    equal(fizzBuzzer.For(3), "Fizz");
    equal(fizzBuzzer.For(6), "Fizz");
});

test("multiple of 5 returns Buzz", function () {
    equal(fizzBuzzer.For(5), "Buzz");
    equal(fizzBuzzer.For(10), "Buzz");
});

test("multiple of 3 and 5 returns FizzBuzz", function () {
    equal(fizzBuzzer.For(15), "FizzBuzz");
    equal(fizzBuzzer.For(30), "FizzBuzz");
});

Solution

Structure

I'm not quite sure why you chose to write your program the way you did. It seems to add complexity to the naive approach of using a normal function, without adding any benefits:

function fizzBuzzer(number) {
    var isBuzz = (number % 5) === 0;
    var isFizz = (number % 3) === 0;

    if (isFizz && isBuzz) { return "FizzBuzz"; }
    if (isBuzz) { return "Buzz"; }
    if (isFizz) { return "Fizz"; }

    return number;
}


Misc

  • parentheses: sometimes you have too many (for example ((isFizz) && (isBuzz)) would be more readable as (isFizz && isBuzz)), and sometimes you could use a bit more (for example, to understand var isBuzz = number % 5 === 0;, you need to remember the precedent of 3 things; I would probably change it to var isBuzz = (number % 5) === 0;).



  • spaces: I wouldn't put a space before ). But I would put one after { and before } to make the code more readable. So if (isBuzz ) {return "Buzz";} for example would become if (isBuzz) { return "Buzz"; }.



  • I like that you wrote unit tests for JavaScript code. You could also include a test for 0, and maybe negative numbers (as they are allowed as input to your function).

Code Snippets

function fizzBuzzer(number) {
    var isBuzz = (number % 5) === 0;
    var isFizz = (number % 3) === 0;

    if (isFizz && isBuzz) { return "FizzBuzz"; }
    if (isBuzz) { return "Buzz"; }
    if (isFizz) { return "Fizz"; }

    return number;
}

Context

StackExchange Code Review Q#64869, answer score: 6

Revisions (0)

No revisions yet.