-
Notifications
You must be signed in to change notification settings - Fork 0
/
args.js
51 lines (41 loc) · 864 Bytes
/
args.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Args{
constructor(pargv){
if(!Array.isArray(pargv))
throw new Error("Argument must be an array");
this.argv = {};
for(let i = 2; i < pargv.length; i++){
let arg = pargv[i];
if(arg.startsWith("--")){
let key = arg.substring(2);
this.argv[key] = pargv[i + 1];
i++;
}else if(arg.startsWith("-")){
let key = arg.substring(1);
this.argv[key] = true;
}
}
}
getValue(key){
return this.argv[key];
}
getValueOrDefault(key, def){
let v = this.getValue(key);
if(v != undefined)
return v;
else
return def;
}
getNumberOrDefault(key, def){
let n = parseFloat(this.argv[key]);
if(Number.isNaN(n))
return def;
else
return n;
}
requireArgument(key, type){
if(this.argv[key] == undefined){
throw new Error("Missing required argument '" + key + "'");
}
}
}
module.exports = Args;