dice.js

I love to play table top roleplaying games. Many of those require that you roll dice. I don't always have any handy, so here is a little method written in javascript to roll dice, given a string in standard dice notation, e.g. '2d20+3'

"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));
  }
};

dice.roll('2d20');