<h1>Functional:</h1>
<pre id="functional"></pre>
<h1>Object-oriented:</h1>
<pre id="object-oriented"></pre>
// Functional approach //
const functionalTrue = (onTrue, onFalse) => onTrue;
const functionalFalse = (onTrue, onFalse) => onFalse;
const isDivisible = (dividend, divisor) => [functionalTrue, ...Array(divisor).fill(functionalFalse)][dividend % divisor];
const functionalFizzBuzz = (n) => {
const divisible_by_three = isDivisible(n, 3);
const divisible_by_five = isDivisible(n, 5);
return divisible_by_three(divisible_by_five("FizzBuzz", "Fizz"), divisible_by_five("Buzz", n));
};
// Object-oriented approach //
const baseBoolean = {
setThen: function(then) { return { ...this, then }; },
setOtherwise: function(otherwise) { return { ...this, otherwise }; },
};
const objectOrientedTrue = {
...baseBoolean,
evaluate: function() { return this.then; },
};
const objectOrientedFalse = {
...baseBoolean,
evaluate: function() { return this.otherwise; },
};
const objectOrientedNumber = {
value: 0,
isaMultipleCache: [objectOrientedFalse],
setValue: function(n) { return { ...this, value: n, isaMultipleCache: [objectOrientedTrue, ...Array(n).fill(objectOrientedFalse)] }; },
isaMultipleOf: function(dividend) { return this.isaMultipleCache[dividend.value % this.value]; }
};
const objectOrientedFizzBuzz = {
for: function(n) {
const number = objectOrientedNumber.setValue(n);
return this.three
.isaMultipleOf(number)
.setThen(
this.five
.isaMultipleOf(number)
.setThen("FizzBuzz")
.setOtherwise("Fizz")
.evaluate()
)
.setOtherwise(
this.five
.isaMultipleOf(number)
.setThen("Buzz")
.setOtherwise(number.value)
.evaluate()
)
.evaluate();
},
three: objectOrientedNumber.setValue(3),
five: objectOrientedNumber.setValue(5),
};
// Output //
const input = Array.from(Array(30), (_,i) => i+1);
const functionalOutput = document.getElementById("functional");
const objectOrientedOutput = document.getElementById("object-oriented");
functionalOutput.innerText = input.map(functionalFizzBuzz);
objectOrientedOutput.innerText = input.map((n) => objectOrientedFizzBuzz.for(n));
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.