Skip to content

Instantly share code, notes, and snippets.

@raduGaspar
Created April 10, 2017 10:08
Show Gist options
  • Save raduGaspar/b3b4c80be0bfea5a5a733fbcb4926a3e to your computer and use it in GitHub Desktop.
Save raduGaspar/b3b4c80be0bfea5a5a733fbcb4926a3e to your computer and use it in GitHub Desktop.
Simple arguments parser
const args = ['-v', 'fileA', 'fileB', 'fileC', 'fileD', 'fileE', 'fileF', '-h', '-l', 'ro']; // process.argv.slice(2);
// supported arguments and their respective methods
const knownArgs = {
'-v': (files) => console.log('files', files),
'-l': (langs) => console.log('langs', langs),
'-h': () => console.log('help'),
};
// parse arguments and provided values
const argsMap = {};
let current;
args.forEach((val) => {
if (knownArgs[val]) {
current = val;
argsMap[current] = [];
}
if (current !== val) {
argsMap[current].push(val);
}
});
// call knownArgs methods with provided arguments
Object.keys(argsMap).forEach((key) => {
knownArgs[key](argsMap[key]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment