Skip to content

Instantly share code, notes, and snippets.

@friendlyanon
Last active October 11, 2018 16:07
Show Gist options
  • Save friendlyanon/0da6994d7b5cf18206bbcd6210c3362f to your computer and use it in GitHub Desktop.
Save friendlyanon/0da6994d7b5cf18206bbcd6210c3362f to your computer and use it in GitHub Desktop.
Beceause everyone needs to show off how they know how to fizzbuzz.
"use strict";
// VERSION 1
// less generic, more performant
function fizzBuzz(start = 1, limit = 100) {
const result = [];
let i3 = start % 3;
let i5 = start % 5;
while (1) {
let str;
if (!i3) str = `Fizz`;
if (!i5) str = `${str || ""}Buzz`;
result.push(str || String(start));
if (++start > limit) break;
if (++i3 === 3) i3 = 0;
if (++i5 === 5) i5 = 0;
}
return result;
}
// VERSION 2
// more generic, less performant
const moduloTestCases = {
"3": "Fizz",
"5": "Buzz"
};
function fizzBuzz(start = 1, limit = 100) {
const result = [];
for (let i = start; i <= limit; ++i) {
let line = "";
for (const test in moduloTestCases) {
if (!(i % test)) line += moduloTestCases[test];
}
result.push(line || String(i));
}
return result;
}
// ------------------------------------------------------------------------- //
for (const message of fizzBuzz()) {
console.log(message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment