Skip to content

Instantly share code, notes, and snippets.

@eli-oat
Last active March 16, 2021 02:01
Show Gist options
  • Save eli-oat/4d8cd62fc994173706922071d9e51aa3 to your computer and use it in GitHub Desktop.
Save eli-oat/4d8cd62fc994173706922071d9e51aa3 to your computer and use it in GitHub Desktop.
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