Skip to content

Instantly share code, notes, and snippets.

@zakcodez
Last active September 18, 2021 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zakcodez/fe0b2bfdbee4a36b51dc35ca285e655d to your computer and use it in GitHub Desktop.
Save zakcodez/fe0b2bfdbee4a36b51dc35ca285e655d to your computer and use it in GitHub Desktop.
A script to parse arguments from an array
// 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;
}
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