Last active
September 13, 2019 13:09
-
-
Save darkwebdev/e347d90a608820c30da66c1217702236 to your computer and use it in GitHub Desktop.
Convert script arguments to an object (ES6)
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 longArgs = arg => { | |
const [ key, value ] = arg.split('='); | |
return { [key.slice(2)]: value || true } | |
}; | |
const flags = arg => [...arg.slice(1)].reduce((flagObj, f) => ({ ...flagObj, [f]: true }), {}); | |
module.exports = () => | |
process.argv | |
.slice(2) | |
.reduce((args, arg) => ({ | |
...args, | |
...((arg.startsWith('--') && longArgs(arg)) || (arg[0] === '-' && flags(arg))) | |
}), {}); | |
// usage: | |
// const args = require('./args')(); | |
// args.help === true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment