m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
path: root/bin
diff options
context:
space:
mode:
authorMarcin Chrzanowski <marcin.j.chrzanowski@gmail.com>2017-07-16 00:15:06 -0400
committerMarcin Chrzanowski <marcin.j.chrzanowski@gmail.com>2017-07-16 00:15:06 -0400
commit74a6ec5fe5d1d10c465c231e64c7b964476464f3 (patch)
treea6a542f9bbf96cb90f1cb316937a8ba004a35889 /bin
parent3e11f6c8268066068c45f4fd760516b8de4a4b28 (diff)
Implement CLI
Diffstat (limited to 'bin')
-rwxr-xr-xbin/dicebag.js46
1 files changed, 46 insertions, 0 deletions
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)
+}