Skip to content

Instantly share code, notes, and snippets.

@dannyrscott
Created February 21, 2014 16:26
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 dannyrscott/9137416 to your computer and use it in GitHub Desktop.
Save dannyrscott/9137416 to your computer and use it in GitHub Desktop.
Node Roller
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;
@dannyrscott
Copy link
Author

Test with:

roller = require('./noderoller');

roller('2d6', function(err, rolls) {
    console.log(arguments);
});

roller('5d8', function(err, rolls) {
    console.log(arguments);
});

roller('3d6+3', function(err, rolls) {
    console.log(arguments);
});


roller('3d6-3', function(err, rolls) {
    console.log(arguments);
});

roller('3d6-+3', function(err, rolls) {
    console.log(arguments);
});

roller('7d20', function(err, rolls) {
    console.log(arguments);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment