Created
February 20, 2020 23:57
-
-
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
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
"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