Created
April 10, 2017 10:08
-
-
Save raduGaspar/b3b4c80be0bfea5a5a733fbcb4926a3e to your computer and use it in GitHub Desktop.
Simple arguments parser
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
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