Created
October 13, 2017 01:52
Read command parameter (argument or option) from generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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