AlgoDaily 02: Fizz Buzz

“We’re given a number n.

Write a function that returns the string representation of all numbers from 1 to n based on the following rules:

If it’s a multiple of 3, represent it as “fizz”.

If it’s a multiple of 5, represent it as “buzz”.

If it’s a multiple of both 3 and 5, represent it as “fizzbuzz”.

If it’s neither, just return the number itself.

As such, fizzBuzz(15) would result in ‘12fizz4buzzfizz78fizzbuzz11fizz1314fizzbuzz’.”

Should be pretty straightfoward:

function fizzBuzz(n) {
	let fizzBuzzed = '';
	for (let i = 1; i <= n; i++) {
		fizzBuzzed += fizzBuzzSingle(i);
	}
	return fizzBuzzed;
}

function fizzBuzzSingle(n) {
	if (n % 5 === 0 && n % 3 === 0) {
		return 'fizzbuzz';
	}
	if (n % 3 === 0) {
		return 'fizz';
	}
	if (n % 5 === 0) {
		return 'buzz';
	}
	return String(n);
}

Trying it out:

fizzBuzz(15);
// "12fizz4buzzfizz78fizzbuzz11fizz1314fizzbuzz"

Tech mentioned