diff options
-rw-r--r-- | README.md | 23 | ||||
-rwxr-xr-x | bin/dicebag.js | 46 | ||||
-rw-r--r-- | package.json | 3 |
3 files changed, 71 insertions, 1 deletions
@@ -4,9 +4,30 @@ A dice expression parser and roller. ## Installation + # in a local node_modules/ npm install --save dicebag + # globally, to use the CLI + npm install -g dicebag -## Usage +## Command-line usage + + dicebag [-p] [<dice expression>] + +If a dice expression is provided, prints the result of rolling those dice and +exits. Otherwise, reads expressions from `stdin` in a loop. + +* `-p` print dice pools (default behavior is to print the dice's sum) + +### Examples + + $ dicebag 1d6 + 1 + $ dicebag "2d8 + 1d4" + 7 + $ dicebag -p "2d8 + 1d4" + [ 5, 3, 4 ] + +## Library usage const { parse, pool, roll } = require('dicebag') diff --git a/bin/dicebag.js b/bin/dicebag.js new file mode 100755 index 0000000..f7b0921 --- /dev/null +++ b/bin/dicebag.js @@ -0,0 +1,46 @@ +#!/usr/bin/env node +/* eslint no-console: 0 */ + +const { parse, roll, pool } = require('../index.js') + +const parseArgs = () => { + const args = process.argv.slice(2) + const parsedArgs = { + roller: roll, + expression: null + } + + while (args.length > 0) { + const arg = args.shift() + if (arg === '-p') { + parsedArgs.roller = pool + } else { + parsedArgs.expression = arg + } + } + + return parsedArgs +} + +const rollDie = (string, roller) => { + try { + const die = parse(string.trim()) + console.log(roller(die)) + } catch (error) { + console.log(error.message) + } +} + +const runIoLoop = (roller) => { + process.stdin.setEncoding('utf8') + process.stdin.on('data', (string) => { + rollDie(string, roller) + }) +} + +const parsedArgs = parseArgs() +if (parsedArgs.expression) { + rollDie(parsedArgs.expression, parsedArgs.roller) +} else { + runIoLoop(parsedArgs.roller) +} diff --git a/package.json b/package.json index 6179d97..1a41e81 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,9 @@ "test": "jest", "lint": "eslint ." }, + "bin": { + "dicebag": "./bin/dicebag.js" + }, "repository": { "type": "git", "url": "git+https://github.com/m-chrzan/dicebag.git" |