/**
* Parses command-line options and stores them in an object.
* This is for development use only.
*
* @param {string[]} args The command-line arguments.
* @returns {object} An object containing the parsed options.
*/
function parseCommandLineOptions(args) {
const options = {}; // Initialize an empty object to store options
let i = 0;
while (i < args.length) {
if (args[i] === '-h' || args[i] === '--help') {
printHelp(); // Call help function if -h or --help is found
return options; // Return empty options after printing help
} else if (args[i].startsWith('--')) {
const optionName = args[i].substring(2); // Extract option name
if (args[i + 1] !== undefined) {
const optionValue = args[i + 1]; // Extract option value
options[optionName] = optionValue; // Store option and value
i += 2; // Skip option and value
} else {
options[optionName] = true; // Store option as a boolean if no value is provided
i++; // Skip option
}
} else {
// Non-option arguments are ignored
i++;
}
}
return options; // Return the parsed options object
}
/**
* Prints help information.
*/
function printHelp() {
console.log('Usage: script.js [-h|--help] [option1] [option2]');
console.log('Options:');
console.log(' -h, --help Show this help message');
console.log(' option1 Value for option1');
console.log(' option2 Value for option2');
}
// Example usage (for testing)
if (require.main === module) {
const args = process.argv.slice(2); // Get command-line arguments
const parsedOptions = parseCommandLineOptions(args); // Parse options
console.log(parsedOptions); // Output the parsed options object
}
Add your comment