@mrprim/dice-roller
Version:
A typescript library for rolling dice using dice notation.
48 lines (47 loc) • 1.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const parseInput = (input) => {
const instructions = [];
input = input.replace(/\s/g, '');
const steps = input.split(/(?=[+-])/g);
steps.forEach((step, index) => {
const stepMatch = /^((?<mod>[+-]){0,1}(?<input>.*)$)/.exec(step);
const modifier = stepMatch?.groups?.mod === '-' ? -1 : 1;
const match = /^(?:(?<x>[\d]+x)){0,1}(?<n>\d+)(?:d(?<d>[\d%F]+)){0,1}(?:kh{0,1}(?<kh>\d+)){0,1}(?:kl(?<kl>\d+)){0,1}(?<reroll>!\d*){0,1}$/.exec(stepMatch?.groups?.input);
if (!match) {
throw new Error('invalid syntax');
}
const numberOfDiceToRoll = parseInt(match?.groups?.n) || 1;
const diceType = parseDiceType(match?.groups?.d);
const timesToReroll = parseInt(match?.groups?.x) || 1;
const numberOfHighestToKeep = parseInt(match?.groups?.kh) || 0;
const numberOfLowestToKeep = parseInt(match?.groups?.kl) || 0;
const rerollMinValue = parseReroll(match?.groups?.reroll, diceType) || 0;
instructions.push({ id: index, numberOfDiceToRoll, diceType, modifier, timesToReroll, numberOfHighestToKeep, numberOfLowestToKeep, rerollMinValue });
});
return instructions;
};
const parseDiceType = (d) => {
if (d === '%') {
return 100;
}
if (d === 'F') {
return d;
}
return parseInt(d) || 1;
};
const parseReroll = (rerollGroup, diceType) => {
if (!rerollGroup) {
return 0;
}
if (rerollGroup.length < 2) {
return getMaxValue(diceType);
}
return parseInt(rerollGroup.substring(1));
};
const getMaxValue = (diceType) => {
if (diceType === 'F')
return 1;
return diceType;
};
exports.default = parseInput;