Skip to content

Instantly share code, notes, and snippets.

@sackeyjason
Last active June 29, 2020 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sackeyjason/773a6a839533fe1dee1ffba95c743cfe to your computer and use it in GitHub Desktop.
Save sackeyjason/773a6a839533fe1dee1ffba95c743cfe to your computer and use it in GitHub Desktop.
99 bottles of beer
function beersong(count) {
let startCount = count;
let song = "";
const countBottles = (c, cap) => {
if (c === -1) return countBottles(startCount);
if (c === 0) return (cap ? 'N' : 'n') + 'o more bottles';
if (c === 1) return '1 bottle'
return `${c} bottles`;
}
for (; count >= 0; --count) {
song += `${countBottles(count, 1)} of beer on the wall, ${countBottles(count)} of beer.\n`;
song += (count > 0)
? "Take one down and pass it around, "
: "Go to the store and buy some more, ";
song += `${countBottles(count - 1)} of beer on the wall.\n\n`;
}
return song;
}
song = beersong(99);
pub.textContent = song;
function beersong2(n) {
const song = [];
const startN = n;
let verse = `{n} bottles of beer on the wall, {n} bottles of beer.
Take one down and pass it around, {o} bottles of beer on the wall.`;
const count = x => x ? x : 'no more';
for (; n >= 0; --n) {
song.push(
verse.replace(/{n}/g, count(n))
.replace(/{o}/, n ? count(n - 1) : startN)
.replace(/^n/, 'N')
.replace(/1 bottles/g, '1 bottle')
.replace((n === 0) && /Take.*,/, 'Go to the store and buy some more,')
);
}
return song.join('\n\n');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment