Last active
April 13, 2019 07:20
-
-
Save trezy/c2242ccae1c64ffff51349ffabb7cdd9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// This is just a mock for our original command | |
const string = '!projects-add -f flag -b "Kirk\'s awesome string" -b "Kirk\'s awesome string" -b "Kirk\'s awesome string" something that won\'t work -r 999'; | |
// Placeholder for the original command string as we replace string arguments | |
let stringWithReplacedArgs = string | |
// Use `.match()` to extract an array of all string arguments | |
const stringArgs = string.match(/(".*?")/g) | |
// Loop over the array of string args and make sure they're replaced with the appropriate index in our replaced string | |
for (const [index, stringArg] of Object.entries(stringArgs)) { | |
stringWithReplacedArgs = stringWithReplacedArgs.replace(stringArg, `{{${index}}}`) | |
} | |
// At this point we have a version of the command string that contains indices in place of the original string arguments, as well as an array of each of the original string arguments. | |
console.log('stringWithReplacedArgs', stringWithReplacedArgs) | |
console.log('stringArgs', stringArgs) | |
/****************************************\ | |
Example usage | |
\****************************************/ | |
// Create an object to store all of our arguments and their values in. This will make the flags and arguments much easier to use later. | |
const argumentHash = {} | |
// Split the updated command string on spaces | |
const splitCommand = stringWithReplacedArgs.split(' ') | |
// Loop over the split command string and find arguments that should have string arguments | |
for (let index = 0; index < splitCommand.length; index++) { | |
const flag = splitCommand[index] | |
const nextArgument = splitCommand[index + 1] | |
// If the next argument in the list starts with a hyphen, it's a flag, so we'll just set the property to true | |
if (/^-/.test(nextArgument)) { | |
argumentHash[flag.replace(/^-/)] = true | |
// If the next argument DOESN'T start with a hyphen, let's assume it's a string value | |
} else { | |
argumentHash[flag.replace(/^-/)] = stringArgs[/{{(\d)}}/.exec(nextArgument)[1]] | |
} | |
} | |
// Now we have an argument hash with all of our flags and arguments neatly packed up. | |
console.log(argumentHash) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment