Created
December 27, 2023 14:08
-
-
Save crashmax-dev/9bb61d0f485580da88635ecf261eb7c7 to your computer and use it in GitHub Desktop.
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
function parseArgs(args) { | |
const parsedArgs = {}; | |
function parseByFlag(args, flag) { | |
for (let i = 0; i < args.length; i++) { | |
if (args[i].startsWith('--')) break | |
if (!parsedArgs[flag]) parsedArgs[flag] = [] | |
parsedArgs[flag].push(args[i]) | |
} | |
} | |
for (let i = 0; i < args.length; i++) { | |
if (args[i].startsWith('--')) { | |
const flag = args[i].slice(2) | |
const argsWithoutFlag = args.slice(i + 1) | |
parseByFlag(argsWithoutFlag, flag) | |
} | |
} | |
return parsedArgs | |
} | |
const args = process.argv.slice(2); | |
const parsedArgs = parseArgs(args); | |
console.log(parsedArgs) | |
// node test.js --directory a b --test c | |
// { directory: [ 'a', 'b' ], test: [ 'c' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment