m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
path: root/bin/dicebag.js
blob: be0a850dd85b399fc274e2d91107151ed79d9f64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env node
/* eslint no-console: 0 */

const { parse, roll, pool } = require('../index.js')

const rollRoller = {
  roll: roll,
  format: value => value
}

const poolRoller = {
  roll: pool,
  format: values => {
    if (values.length === 0) {
      return '[]'
    } else {
      return '[ ' + values.reduce((acc, next) => (
        acc + ', ' + String(next)
      )) + ' ]'
    }
  }
}

const parseArgs = () => {
  const args = process.argv.slice(2)
  const parsedArgs = {
    roller: rollRoller,
    expression: null
  }

  while (args.length > 0) {
    const arg = args.shift()
    if (arg === '-p') {
      parsedArgs.roller = poolRoller
    } else {
      parsedArgs.expression = arg
    }
  }

  return parsedArgs
}

const rollDie = (string, roller) => {
  try {
    const die = parse(string)
    const roll = roller.roll(die)
    console.log(roller.format(roll))
  } catch (error) {
    console.log(error.message)
  }
}

const runIoLoop = (roller) => {
  console.log("Type 'quit' or 'exit' to exit")
  process.stdin.setEncoding('utf8')
  process.stdin.on('data', (string) => {
    string = string.trim()
    if (string === 'exit' || string === 'quit') {
      process.exit(0)
    }

    rollDie(string, roller)
  })
}

const parsedArgs = parseArgs()
if (parsedArgs.expression) {
  rollDie(parsedArgs.expression, parsedArgs.roller)
} else {
  runIoLoop(parsedArgs.roller)
}