-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
98 lines (81 loc) · 2.83 KB
/
index.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
96
97
98
module.exports = function(argv , options = { mergeSingleFlage : false }) {
return parse(argv, options.mergeSingleFlage)
}
function convertArgToPremitive(value) {
if(isBoolean(value)){
return toBoolean(value);
}else if(isNumber(value)){
return toNumber(value);
}
return value;
}
function isBoolean(value){
return /^((true|false))/g.test(value);
}
function toBoolean(value){
if( value ){
switch(value.toString().toLowerCase()){
case "true": return true;
case "false": return false;
}
}
return value;
}
function isNumber(value){
if (typeof x === 'number') return true;
if (/^0x[0-9a-f]+$/i.test(value)) return true;
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(value);
}
function toNumber(value){
return parseFloat(value);
}
// private Methods
function parseMatch(match , single = true) {
if (match !== null) {
match = match['groups'];
match.single = single;
}else match = null;
return match;
}
function isMatched(match) {
return match !== null ;
}
function isValueNext(match) {
return (isMatched(match) && ( (match.value === undefined) || (match.value === null)) );
}
// public Methods
function singleCharOption(arg , mergeSingleFlage = false) {
return !mergeSingleFlage ? parseMatch(/^-(?<option>\w)(?<value>\S*)?$/g.exec(arg)) : parseMatch(/^-(?<option>\w+)$/g.exec(arg));
}
function wordOption(arg ){
return parseMatch( /^--(?<option>\w+)(=?(?<value>\S*))?$/g.exec(arg) , false);
}
function isValidNext(nextMatched){
return (singleCharOption(nextMatched) || wordOption(nextMatched)) == null ? true : false ;
}
function parse(argv = [] , mergeSingleFlage = false){
let matched ;
let argvParsed = {$ : []}
for(let x = 0 ; x < argv.length ; x++){
matched = singleCharOption(argv[x] , mergeSingleFlage) || wordOption(argv[x]);
if(matched === null){
argvParsed.$.push(argv[x]);
continue;
}else if(mergeSingleFlage && matched.single){
for ( let option of matched.option.split('')){
argvParsed[option] = true ;
}
continue;
}
else if(isValueNext(matched)){
if(isValidNext(argv[x+1])){
(matched.single && (matched.value == undefined)) ? matched.value = true : matched.value = null;
argvParsed[matched.option] = convertArgToPremitive(argv[++x] ?? matched.value) ;
continue;
}
}
(matched.single && (matched.value == undefined)) ? matched.value = true : '';
argvParsed[matched.option] = convertArgToPremitive(matched.value) ;
}
return argvParsed;
}