Skip to content

Instantly share code, notes, and snippets.

@eli-oat eli-oat/dice.js

Created Feb 20, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.