Created
June 24, 2021 04:12
-
-
Save asunar/9f50ab5c3312ba0050c96eb5c437cc39 to your computer and use it in GitHub Desktop.
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
// Copy and paste it into Chrome devtools console to run it | |
let cliParser = (args) => { | |
let keyValueList = [] | |
let keyBucket = [] | |
let valueBucket = [] | |
let isKey = false | |
let isInsideQuote = false | |
args += '-' //to add last key value pair | |
args.split('').forEach(x =>{ | |
// console.log('Processing', x) | |
// console.log('isKey', isKey) | |
// console.log('isInsideQuote', isInsideQuote) | |
//console.log(x) | |
switch (x) { | |
case '-': | |
if(isInsideQuote){ | |
valueBucket.push(x) | |
} else { | |
if(keyBucket.length > 0){ | |
keyValueList.push({ | |
key: keyBucket.join(''), | |
value: valueBucket.join('') | |
}) | |
keyBucket= [] | |
valueBucket = [] | |
} | |
isKey = true | |
} | |
break; | |
case "'": | |
isInsideQuote = !isInsideQuote | |
break; | |
case " ": | |
if(isKey){ | |
isKey = false | |
} else { | |
if(isInsideQuote){ | |
valueBucket.push(x) | |
} | |
} | |
break | |
default: | |
if(isKey){ | |
keyBucket.push(x) | |
} | |
else { | |
valueBucket.push(x) | |
} | |
} | |
// console.log('keyBucket', keyBucket) | |
// console.log('valueBucket', valueBucket) | |
// console.log('keyValueList', keyValueList) | |
}) | |
console.log('keyValueList', keyValueList) | |
} | |
cliParser("-key 'my report-1.txt' -key2 -key3 value3") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment