Can someone please correct this code of mine for FizzBuzz? There seems to be a small mistake. This code below prints all the numbers instead of printing only numbers that are not divisible by 3 or 5.
Write a program that prints the numbers from
1
to100
. But for multiples of three, print"Fizz"
instead of the number, and for the multiples of five, print"Buzz"
. For numbers which are multiples of both three and five, print"FizzBuzz"
.
function isDivisible(numa, num) {
if (numa % num == 0) {
return true;
} else {
return false;
}
};
function by3(num) {
if (isDivisible(num, 3)) {
console.log("Fizz");
} else {
return false;
}
};
function by5(num) {
if (isDivisible(num, 5)) {
console.log("Buzz");
} else {
return false;
}
};
for (var a=1; a<=100; a++) {
if (by3(a)) {
by3(a);
if (by5(a)) {
by5(a);
console.log("\n");
} else {
console.log("\n");
}
} else if (by5(a)) {
by5(a);
console.log("\n");
} else {
console.log(a+"\n")
}
}
check this out!
Functional style! JSBin Demo
Just want to share my way to solve this
In case someone is looking for other solutions: This one is a pure, recursive, and reusable function with optionally customizable parameter values:
from > till
is the anchor to break the recursion. Since it returns false untilfrom
is higher thantill
, it goes to the next statement (console.log
):Object.keys
returns an array of object properties in the givenruleMap
which are3
and5
by default in our case.from
(0 as rest).filter
method returned an empty array ([]
, no results found), it outputs just the currentfrom
value because thejoin
method at the end finally returns just an empty string (""
) which is a falsy value.console.log
always returnsundefined
, it goes to the next statement and calls itself again incrementing thefrom
value by1
.