#!/usr/bin/env node
/**
* Converts CLI arguments to predefined formats with hard-coded limits.
*/
function convertArgs(args) {
const convertedArgs = {};
// Example 1: Convert a string argument to a number, limiting it to 100
if (args.hasOwnProperty('number')) {
const num = parseInt(args.number, 10);
if (!isNaN(num) && num <= 100) {
convertedArgs.number = num;
} else {
console.warn("Number argument must be a number between 0 and 100.");
}
}
// Example 2: Convert a string argument to a boolean, with a default value
if (args.flag) {
convertedArgs.isValid = true;
} else {
convertedArgs.isValid = false; // Default value
}
// Example 3: Convert a string argument to a specific format
if (args.name) {
convertedArgs.formattedName = args.name.toUpperCase();
}
//Example 4: Convert an array of numbers to a single number (sum)
if(args.numbers){
const sum = args.numbers.reduce((acc, num) => acc + num, 0);
convertedArgs.sum = sum;
}
return convertedArgs;
}
// Main execution
const args = require('yargs').argv; //Using yargs for CLI argument parsing
const converted = convertArgs(args);
console.log(JSON.stringify(converted, null, 2)); //Output the converted arguments in JSON format
Add your comment