Created
February 21, 2014 16:26
-
-
Save dannyrscott/9137416 to your computer and use it in GitHub Desktop.
Node Roller
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
var roller = function(toRoll, callback) { | |
toRoll = toRoll || ''; | |
rollData = toRoll.split('d'); | |
if (rollData.length !== 2) | |
return callback(new Error('Invalid roll format')); | |
var die, | |
dice = [], | |
total = 0, | |
dieSize = rollData[1], | |
modifier = false; | |
if (dieSize.indexOf('+') !== -1) { | |
modifier = Number(dieSize.substring(dieSize.indexOf('+'), dieSize.length)); | |
dieSize = dieSize.split('+')[0]; | |
} | |
else if (dieSize.indexOf('-') !== -1) { | |
modifier = Number(dieSize.substring(dieSize.indexOf('-'), dieSize.length)); | |
dieSize = dieSize.split('-')[0]; | |
} | |
for (var i = 0; i < rollData[0]; i++) { | |
die = Math.floor(Math.random() * dieSize) + 1; | |
if (modifier) | |
die += modifier; | |
if (isNaN(die)) | |
return callback(new Error('Invalid roll format')); | |
total += die; | |
dice.push(die); | |
} | |
callback(null, {total: total, dice: dice}); | |
}; | |
module.exports = roller; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test with: