Skip to content

Instantly share code, notes, and snippets.

@petomalina
Created January 25, 2015 22:09
Show Gist options
  • Save petomalina/b40c6ef7cb10b82cc622 to your computer and use it in GitHub Desktop.
Save petomalina/b40c6ef7cb10b82cc622 to your computer and use it in GitHub Desktop.
Node.js input arguments parsing algorithm
###
Parses given array of input arguments and recognizes commands,
subcommands and switches with their values
@param [argv] argument list to parse
@return [ Array, Object] An array of commands and object of switches
###
parseArguments = (argv) ->
commands = []
switches = { }
for y in [0...argv.length]
break if argv[y].trim()[0] is '-' # commands are till first switch
commands.push(argv[y].trim())
skip = false # skip the value if it belongs to switch
for i in [y...argv.length]
if skip
skip = false
continue
if i + 1 < argv.length and argv[i+1].trim()[0] isnt '-'
switches[argv[i]] = argv[i+1] # assign value to the given switch
skip = true
else
switches[argv[i]] = null # switch has no value, give it null
return [ commands, switches ]
# EXAMPLE
[commands, switches] = parseArguments(process.argv.slice(2))
# assume input: install simple_application --verbose all --log install_log.txt -q -f
# output will be: [ [ install, simple_application ], { '--verbose': all, '--log': install_log.txt, '-q': null, '-f', null } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment