Skip to content

Instantly share code, notes, and snippets.

@EricCrosson
Created August 29, 2018 17:34
Show Gist options
  • Save EricCrosson/71d50eba5b2f419aa861affc473c32b1 to your computer and use it in GitHub Desktop.
Save EricCrosson/71d50eba5b2f419aa861affc473c32b1 to your computer and use it in GitHub Desktop.
Dispatcher design-pattern for docopt subcommands
const docopt = require('docopt').docopt
const docstring = `
Naval Fate.
Usage:
naval_fate ship new <name>...
naval_fate ship <name> move <x> <y> [--speed=<kn>]
naval_fate ship shoot <x> <y>
naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
naval_fate -h | --help
naval_fate --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
`
const subcommands = {
ship: async function(args) {
console.log('subcommand: ship')
},
mine: async function(args) {
console.log('subcommand: mine')
}
}
async function main() {
let args = docopt(docstring)
console.log(args)
Object.keys(subcommands)
.forEach(async (subcommand) =>
args[subcommand] && await subcommands[subcommand](args))
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment