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

Functional, recursive FizzBuzz in JavaScript

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

Problem

I was talking to a coworker about over engineering things, which somehow lead to me over engineering the hell out of fizzbuzz. I went for a functional recursive solution in JavaScript. What do you think?

Full disclosure: my knowledge of functional programming begins and ends at "functions are king" and "no side effects" so I would LOVE some feedback regarding functional programming. But please point out other inefficiencies as well.

fizzbuzz();

function fizzbuzz() {
    var i = 1;
    var result = [];

    (function loop() {
        var str = '';
        str += fizz(i);
        str += buzz(i);

        result.push(ifFalsy(str, i));

        if (isLt100(i++)) {
            loop();
        }
    })();

    print(result.join(', '));
}

function fizz(num) {
    return isDivBy3(num) ? 'fizz' : '';
}

function buzz(num) {
    return isDivBy5(num) ? 'buzz' : '';
}

function isDivBy3(num) {
    return num % 3 === 0;
}

function isDivBy5(num) {
    return num % 5 === 0;
}

function isLt100(num) {
    return num < 100;
}

function ifFalsy(value, fallback) {
    return !value ? fallback : value;
}

function print(str) {
    console.log(str);
}

Solution

Functional programming is not about writing as many functions as you can. I would suggest to start with a function library (e.g. Ramda) and write as few new functions as needed, taking advantage of currying.

Obviously, your loop function has side effects: it modifies result and i.

Without going to deep into FP rabbit hole, your function could look like this:



function getFizzBuzzArray() {
function getFizzBuzz(v) {
var ret = R.concat(
v % 3 === 0 ? 'fizz' : '',
v % 5 === 0 ? 'buzz' : ''
);

return ret || v;
}

return R.map(getFizzBuzz, R.range(1, 101));
}

document.write(getFizzBuzzArray());

``

Context

StackExchange Code Review Q#112544, answer score: 8

Revisions (0)

No revisions yet.