Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Kerrick
Last active March 11, 2018 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kerrick/1ad92c898d8b7d9f99631a72d68493cf to your computer and use it in GitHub Desktop.
Save Kerrick/1ad92c898d8b7d9f99631a72d68493cf to your computer and use it in GitHub Desktop.
ES2018 Dice Roller

Roll

Roll any number of dice on your command line, including modifiers!

Dependencies

Requrise node v8.x or higher.

Usage

$ node index.js roll1 [, roll2, ..., rollN]

Format your rolls as [integer]d[size][+ or -][modifier], such as 1d20+4 or 2d6-1.

Assuming you alias roll to node index.js:

$ roll 1d20+6 2d6+4 1d6-1 1d4
11 = 1d20 (5) + 6
6 = 1d6 (1) + 1d6 (1) + 4
2 = 1d6 (3) + -1
1 = 1d4 (1) + 0
// Utilities
const times = n => Array.from({ length: n }).map(n => n + 1);
const compact = [(acc, x) => x ? [...acc, x] : acc, []];
const sum = [(acc, n) => acc + n, 0];
const randBetween = (lower, upper) => Math.floor(Math.random() * (upper - lower + 1) + lower);
// Parsing
const parseInput = die => die.replace(/\s/g, '').match(/(\d*)d(\d+)(?:([\+-])(\d+))?/);
const operators = {
'+': str => parseInt(str, 10),
'-': str => -1 * parseInt(str, 10),
};
const toNumber = (operator, modifier) => operators[operator] ? operators[operator](modifier) : 0;
// Dice
const rollDie = size => randBetween(1, size);
const generateDiceRolls = ([str, count, size, operator, modifier]) => ({
count,
size,
rolls: times(count).map(() => rollDie(size)),
modifier: toNumber(operator, modifier),
});
const total = roll => roll.rolls.reduce(...sum) + roll.modifier;
// Display
const individuals = roll => times(roll.count)
.map((n, i) => `1d${roll.size} (${roll.rolls[i]})`)
.join(' + ');
const formatRoll = roll => `${total(roll)} = ${individuals(roll)} + ${roll.modifier}`;
// Application
const [, , ...dice] = process.argv;
const rolls = dice
.map(parseInput)
.reduce(...compact)
.map(generateDiceRolls)
.map(formatRoll);
rolls.forEach(roll => console.log(roll));
{
"name": "roll",
"version": "1.0.0",
"description": "Roll arbitrary dice on the command line",
"main": "index.js",
"repository": "https://github.com/Kerrick/roll",
"author": "Kerrick Long <me@kerricklong.com>",
"license": "MIT"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment