Skip to content

Instantly share code, notes, and snippets.

@eli-oat
Created February 20, 2020 23: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 eli-oat/d41134fbea7e2d1269404f9d9a06a063 to your computer and use it in GitHub Desktop.
Save eli-oat/d41134fbea7e2d1269404f9d9a06a063 to your computer and use it in GitHub Desktop.
Roll the dice | simple code that can parse standard dice notation (e.g. '2d20+3') and return a more or less random result within that range
"use strict";
const dice = {
validate: (diceNotation) => {
const match = /^(\d+)?d(\d+)([+-]\d+)?$/.exec(diceNotation);
if (!match) {
throw "Invalid dice notation: " + diceNotation;
} else {
return match;
}
},
diceData: (diceNotation) => {
const match = dice.validate(diceNotation);
if (match) {
const diceInfo = {
"numberOfDice": typeof match[1] === "undefined" ? 1 : parseInt(match[1]),
"sidesOfDice": parseInt(match[2]),
"diceModifier": typeof match[3] === "undefined" ? 0 : parseInt(match[3])
};
return diceInfo;
}
},
math: (diceData) => {
let total = 0;
for (let i = 0; i < diceData.numberOfDice; i++) {
total += Math.floor(Math.random() * diceData.sidesOfDice) + 1;
}
total += diceData.diceModifier;
return total;
},
roll: (humanInput) => {
return dice.math(dice.diceData(humanInput));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment