Skip to content

Instantly share code, notes, and snippets.

@garrydzeng
Created October 13, 2017 01:52
Read command parameter (argument or option) from generator
function* getopt(argv) {
let cache = null
// ignore execution program & script filename by call to .slice() function.
for (let node of argv.slice(2)) {
const match = /^--([a-z][0-9a-z-]*)(?:=(.*))?$/i.exec(node)
// hanlde cache first...
if (cache) {
// yield previous option with TRUE (no value matched) or current argument.
const value = match ? true : node
yield {
name: cache,
isArgument: false,
value: value
}
cache = null
// discard argument if assigned to previous option...
if (match == null) {
continue
}
}
// save & continue if this option doesn't matched a value.
if (match && !match[2]) {
cache = match[1]
continue
}
const mismatch = (match == null)
yield {
name: mismatch ? undefined : match[1],
isArgument: mismatch,
value: mismatch ? node : match[2]
}
}
// handle last option without value
if (cache) {
yield {
name: cache,
isArgument: false,
value: true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment