Created
December 11, 2018 19:09
-
-
Save MKRhere/a4833c20aaabe250bfc2e039c962bd64 to your computer and use it in GitHub Desktop.
26 line forgiving argv parser
This file contains hidden or 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 VALUES = Symbol('VALUES'); | |
const Parser = (argv, { subcommands } = {}) => { | |
argv = argv.slice(2); | |
return { | |
get (key) { | |
if (key === VALUES) { | |
return argv.filter((x, i) => | |
(!subcommands || i !== 0) && !x.startsWith('-') | |
&& (!argv[i - 1] || !argv[i - 1].startsWith('-'))); | |
} else if (key.startsWith('-')) { | |
if (key.startsWith('--')) { | |
const i = argv.findIndex(x => x === key); | |
if (i === -1) return null; | |
if (argv[i + 1] && !argv[i+1].startsWith('-')) | |
return argv[i + 1]; | |
return true; | |
} | |
} else { | |
if (subcommands && argv[0] === key) | |
return argv.slice(1).findIndex(x => x === key) !== -1; | |
if (argv.findIndex((x, i) => | |
x === key && (!argv[i - 1] || !argv[i-1].startsWith('-')) | |
) !== -1) return true; | |
} | |
return null; | |
} | |
}; | |
}; | |
/* -- */ | |
const parser = Parser(process.argv); | |
console.log(parser.get("--thing")); | |
/* -- */ | |
module.exports = Parser; | |
module.exports.VALUES = VALUES; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment