Created
September 12, 2013 17:20
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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