fizzBuzz (array)
with Carmen Salas • 2024/10/30
Code Challenge
/*
## PEDAC
**Problem**
input: Number **n** which indicates the upper limit of the loop
output: Array **res** which lists elements either as a String representation of the number itself or the words "fizz", "buzz", or "fizzbuzz", ranging from 1 to **n**
**Examples/Edge Cases:**
1 -> ["1"]
0 -> []
**Data Structure**
- Array
- String
- Conditionals
**Algorithm**
1. Check if n > 0. (otherwise return [])
2. Initialize an empty result array.
3. Iterate from 1 to **n**.
3.a. If item is divisible by both 3 and 5: push "fizzbuzz" into resulting array.
3.b. If item is divisible by only 3: push "fizz" into resulting array.
3.c. If item is divisible by only 5: push "buzz" into resulting array.
3.d. If item is neither of the above, turn it into a String representation of
itself and push it into the resulting array.
4. Return the resulting array.
*/
// updated: it's possible to map directly without fill!
// just have to destruct the array so it's iterable.
function solution(n) {
if (n <= 0) { return []; } // Step 1
return [...Array(n)]
.map((val, i, arr) => { // Steps 2,3,4
// Steps 3.a to 3.d
let str = '';
// shoutout to the algorithm Isaac shared the other day!
if ((i+1) % 3 === 0) { str += "Fizz"; }
if ((i+1) % 5 === 0) { str += "Buzz"; }
if (str.length === 0) { str = String(i+1); }
return str;
});
}
Last updated