UNPKG

@mrprim/dice-roller

Version:

A typescript library for rolling dice using dice notation.

52 lines (51 loc) 2.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const rand_1 = require("./rand"); const parseInput_1 = require("./parseInput"); const roll = (input, verbose) => { const instructions = (0, parseInput_1.default)('' + input); let id = 0; const details = instructions.reduce((final, { id: instructionId, diceType, numberOfDiceToRoll, modifier, timesToReroll, numberOfHighestToKeep, numberOfLowestToKeep }) => { for (let i = 0; i < timesToReroll; i++) { let groupResults = []; for (let k = 0; k < (diceType === 1 ? 1 : numberOfDiceToRoll); k++) { const r = { id: id++, instructionId, diceType, modifier, value: 0, discard: false }; r.value = (diceType === 1) ? numberOfDiceToRoll : rollADie(diceType); r.value = r.value * modifier; groupResults.push(r); } groupResults = handleDiscards(groupResults, numberOfHighestToKeep, numberOfLowestToKeep); final = final.concat(groupResults); } return final; }, []); const total = details.reduce((total, r) => r.discard ? total : (total + r.value), 0); if (verbose) { return { total, instructions, details }; } else { return total; } }; const handleDiscards = (results, kh, kl) => { if (!kh && !kl) return results; results = results.sort((a, b) => a.value < b.value ? -1 : 1).map(r => ({ ...r, discard: true })); console.log('before', results); if (kl) { results = results.map((r, index) => ({ ...r, discard: index < kl ? false : r.discard })); } if (kh) { results = results.map((r, index) => ({ ...r, discard: index >= results.length - kh ? false : r.discard })); } return results.sort((a, b) => a.id > b.id ? 1 : -1); }; const rollADie = (sides) => { if (sides === 'F') { return Math.floor((0, rand_1.default)()() * 3) - 1; } if (typeof sides === 'number') { return Math.floor((0, rand_1.default)()() * sides) + 1; } }; exports.default = roll;