-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathep-argv-es6.js
95 lines (82 loc) · 3.04 KB
/
ep-argv-es6.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class Pn_argv{
constructor(argv , options = { mergeSingleFlage : true }){
this.argv = argv;
this.argvParsed = { $ : []}
this.options = options;
}
// private Methods
#parseMatch(match , single = true) {
if (match !== null) {
match = match['groups'];
match.single = single;
}else match = null;
return match;
}
#isMatched(match) {
return match !== null ;
}
#isValueNext(match) {
return (this.#isMatched(match) && ( (match.value === undefined) || (match.value === null)) );
}
// public Methods
singleCharOption(arg){
return !this.options.mergeSingleFlage ? this.#parseMatch(/^-(?<option>\w)(?<value>\S*)?$/g.exec(arg)) : this.#parseMatch(/^-(?<option>\w+)$/g.exec(arg));
}
wordOption(arg ){
return this.#parseMatch( /^--(?<option>\w+)(=?(?<value>\S*))?$/g.exec(arg) , false);
}
#isValidNext(nextMatched){
return (this.singleCharOption(nextMatched) || this.wordOption(nextMatched)) == null ? true : false ;
}
parse(){
let matched ;
for(let x = 0 ; x < this.argv.length ; x++){
matched = this.singleCharOption(this.argv[x]) || this.wordOption(this.argv[x]);
if(matched === null){
this.argvParsed.$.push(this.argv[x]);
continue;
}else if(this.options.mergeSingleFlage && matched.single){
for ( let option of matched.option.split('')){
this.argvParsed[option] = true ;
}
continue;
}
else if(this.#isValueNext(matched)){
if(this.#isValidNext(this.argv[x+1])){
(matched.single && (matched.value == undefined)) ? matched.value = true : matched.value = null;
this.argvParsed[matched.option] = this.convertArgToPremitive(this.argv[++x] ?? matched.value) ;
continue;
}
}
(matched.single && (matched.value == undefined)) ? matched.value = true : '';
this.argvParsed[matched.option] = this.convertArgToPremitive(matched.value) ;
}
return this.argvParsed;
}
convertArgToPremitive(value){
if(this.#isBoolean(value)){
return this.toBoolean(value);
}else if(this.#isNumber(value)){
return this.toNumber(value);
}
return value;
}
#isBoolean(value){
return /^((true|false))/g.test(value);
}
toBoolean(value){
if( value ){
switch(value.toString().toLowerCase()){
case "true": return true;
case "false": return false;
}
}
return value;
}
#isNumber(value){
return /^(?<digit>\d+)(\.)?(?<frac>\d*)?$/gi.test(value) ;
}
toNumber(value){
return parseFloat(value);
}
}