Skip to content

Instantly share code, notes, and snippets.

@smithcommajoseph
Created September 12, 2013 17:20
Show Gist options
  • Save smithcommajoseph/6540980 to your computer and use it in GitHub Desktop.
Save smithcommajoseph/6540980 to your computer and use it in GitHub Desktop.
a quick demo of how to code 99 beers on the wall in js
(function(){
var arr = [],
START_COUNT = 99;
TPL = '%count bottles of beer on the wall, %count bottles of beer, take 1 down, pass it around, %nextCount bottles of beer on the wall\r\n';
function init () {
for (var i = START_COUNT; i > 0; i--) {
arr.push(hydrate({count: i, nextCount: i-1}));
}
console.log(arr.join(''));
}
function tokenize() {
var tokens = [];
TPL
.match(/%\w+/g)
.unique()
.forEach( function(tokenName, k) {
tokens.push( {regEx: new RegExp(tokenName, 'g'), variable: getVariableName(tokenName)} );
});
return tokens;
}
function getVariableName(tokenName) {
return tokenName.slice(1);
}
function hydrate(ob) {
var tokens = tokenize(),
hydratedTpl = TPL;
tokens.forEach(function(token){
hydratedTpl = hydratedTpl.replace(token.regEx, ob[token.variable]);
});
return hydratedTpl;
}
// a little brute force
Array.prototype.unique = function unique () {
return this.reduce(function(prev, curr){
if (!~prev.indexOf(curr)) prev.push(curr);
return prev;
}, []);
};
init();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment