Skip to content

Instantly share code, notes, and snippets.

@eli-oat

eli-oat/dice.ts

Last active Mar 16, 2021
Embed
What would you like to do?
A dice rolling class
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;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment