Skip to footer navigation.

« Oatmeal

Posts tagged ts

Follow this tag's bespoke rss feed or return to the list of all tags.

dice.ts

Migrated that dice rolling class to typescript 🤷

interface Dice {
    numberOfDice: number;
    sidesOfDice: number;
    diceModifier: number;
}

interface LogEntry {
    timestamp: string;
    input: string;
    result: number;
}

class DiceRoller {

  readonly log: LogEntry[];

  constructor() {
    this.log = [];
  }

  roll(humanInput: string): number {
    const rollResult = this.tallyRolls(this.parseDice(humanInput));
    const rightNow = new Date();
    let logEntry = {
      "timestamp": rightNow.toISOString(),
      "input": humanInput,
      "result": rollResult
    }
    this.log.push(logEntry);
    return rollResult;
  }

  private parseDice(diceNotation: string): Dice | undefined {
    const match = this.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;
    }
  }

  private validate(diceNotation: string): RegExpExecArray | undefined {
    const match = /^(\d+)?d(\d+)([+-]\d+)?$/.exec(diceNotation);
    if (!match) {
      throw "Invalid dice notation: " + diceNotation;
    } else {
      return match;
    }
  }

  private tallyRolls(diceData: Dice): number {
    let total = 0;
    for (let i = 0; i < diceData.numberOfDice; i++) {
      total += Math.floor(Math.random() * diceData.sidesOfDice) + 1;
    }
    total += diceData.diceModifier;
    return total;
  }

};

Works the same as dice.js 2.0.

Also lives as a gist.