Skip to content

Instantly share code, notes, and snippets.

@nexpr
Created June 3, 2018 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nexpr/63859ba1bdb87be7caa3e6fd61cfae6f to your computer and use it in GitHub Desktop.
Save nexpr/63859ba1bdb87be7caa3e6fd61cfae6f to your computer and use it in GitHub Desktop.

Node.js 引数のパーサ一段階目

いったん key=value の配列に直したほうが扱いやすそうだったので その形に変換する

  • value がないのは [key, null]
  • key がないのは [null, value]
  • --- 単体は [null, "--"][null, "-"]
  • いまのとこ boolean 型の key 指定がないので --ab 10 で 10 は単体にならない
    • 3 つ目にフラグで argv の要素が別れていたかもたせる?
import parseFirst from "./parseFirst"
parseFirst(["-a", "1", "--bc-d", "3", "--ae", "--bb=a31", "-r=100", "-zxyz", "-", "qq", "--", "89", "-1", "-u7"])
/*
[
["a", "1"],
["bc-d", "3"],
["ae", null],
["bb", "a31"],
["r", "100"],
["z", null],
["x", null],
["y", null],
["z", null],
[null, "-"],
[null, "qq"],
[null, "--"],
[null, "89"],
["1", null],
["u", "7"],
]
*/
export default function(args){
const result = {
flush(){
if(this.buf){
this.values.push([this.buf, null])
this.buf = null
}
},
append(key, value = null){
this.values.push([key, value])
},
keep(key){
if(this.buf){
throw new Error("already has keeped value.")
}
this.buf = key
},
single(value){
if(this.buf){
this.values.push([this.buf, value])
this.buf = null
}else{
this.values.push([null, value])
}
},
buf: null,
values: [],
}
for(const arg of args){
if(arg === "--" || arg === "-"){
result.flush()
result.append(null, arg)
}else if(arg.startsWith("--")){
result.flush()
const str = arg.substr(2)
if(str.includes("=")){
const [, key, value] = str.match(/^([^=]*)=?(.*)$/)
result.append(key, value)
}else{
result.keep(str)
}
}else if(arg.startsWith("-")){
result.flush()
const str = arg.substr(1)
const [, chars, body] = str.match(/^(.[a-zA-Z]*)=?(.*)$/)
const last = chars.substr(-1)
for(const char of chars.slice(0, -1)){
result.append(char)
}
if(body){
result.append(last, body)
}else{
result.keep(last)
}
}else{
result.single(arg)
}
}
result.flush()
return result.values
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment