Skip to content

Instantly share code, notes, and snippets.

@madigan
Created January 21, 2017 04:57
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 madigan/3788793273208d61bf33c36e668eb4b9 to your computer and use it in GitHub Desktop.
Save madigan/3788793273208d61bf33c36e668eb4b9 to your computer and use it in GitHub Desktop.
JavaScript used to simulate a die roll
/**
* Expects input in the standard format- 1d6+2 or 1d12-1 or 4d4
*/
function roll(dieCode) {
var total = 0;
var results = dieCode.match(/([0-9]+)d([0-9]+)([\-\+][0-9]+)?/);
if(results !== null) {
for(var i = 0; i < parseInt(results[1]); i++) {
total += Math.floor(Math.random() * parseInt(results[2])) + 1;
}
if(parseInt(results[3])) {
total += parseInt(results[3]);
}
}
return total;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment