Last active
September 18, 2021 02:58
-
-
Save zakcodez/fe0b2bfdbee4a36b51dc35ca285e655d to your computer and use it in GitHub Desktop.
A script to parse arguments from an array
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
// Call with either an array of arguments such as | |
// ["--foo=bar", "--bar", "baz"] | |
// or from the process in Node: process.argv.slice(2); | |
function parseArguments(argv) { | |
const parsedArgs = { | |
_: [], | |
flags: {} | |
} | |
argv.forEach((argument) => { | |
if (argument.startsWith("--")) { | |
argument = argument.replace("--", ""); | |
if (argument.indexOf("=") === -1) { | |
parsedArgs.flags[argument] = true; | |
} else { | |
const argumentName = argument.split("=")[0]; | |
const argumentValue = argument.split("=")[1]; | |
parsedArgs.flags[argumentName] = argumentValue; | |
} | |
} else { | |
parsedArgs._.push(argument); | |
} | |
}); | |
return parsedArgs; | |
} |
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
interface IParsedFlags { | |
[key: string]: string | boolean; | |
} | |
interface IParsedArgs { | |
_: string[]; | |
flags: IParsedFlags; | |
} | |
function parseArguments(argv: string[]) { | |
const parsedArgs: IParsedArgs = { | |
_: [], | |
flags: {} | |
} | |
argv.forEach((argument) => { | |
if (argument.startsWith("--")) { | |
argument = argument.replace("--", ""); | |
if (argument.indexOf("=") === -1) { | |
parsedArgs.flags[argument] = true; | |
} else { | |
const argumentName = argument.split("=")[0]; | |
const argumentValue = argument.split("=")[1]; | |
parsedArgs.flags[argumentName] = argumentValue; | |
} | |
} else { | |
parsedArgs._.push(argument); | |
} | |
}); | |
return parsedArgs; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment