14 ms·
Sure maybe something like this. It's not very performant, but it uses some math skills: console.clear(); /** naive python like range in JS */ function*
by johnsonjo 7y ago
Sure maybe something like this. It's not very performant, but it uses some math skills:
console.clear();
/** naive python like range in JS */
function* range (beg, end) {
for(let i = beg; i < end; ++i) {
// stringify the number
yield '' + i;
}
}
function buzz (stringNum) {
const lastChar = stringNum.charAt(stringNum.length - 1);
return lastChar === '5' || lastChar === '0';
}
const mapping = [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1];
function fizz (stringNum) {
return (
stringNum
// get each character of the string
.split('')
// find out if total digits are divisible by three.
.reduce((acc, x) => (acc + mapping[x]) % 3, 0) === 0
);
}
function fizzBuzz (stringNum) {
const f = fizz(stringNum), b = buzz(stringNum);
if(f && b) {
return 'FizzBuzz';
} else if (f) {
return 'Fizz';
} else if (b) {
return 'Buzz';
} else {
return stringNum;
}
}
const nums = [...range(1,1001)];
const result = nums
// main algo
.map(fizzBuzz)
console.log(result.join('\n'));
EDIT: sorry I didn't see your other reply below another comment. I now see this does not fulfill the requirements.