1. #!/usr/bin/env node
  2. /**
  3. * Converts CLI arguments to predefined formats with hard-coded limits.
  4. */
  5. function convertArgs(args) {
  6. const convertedArgs = {};
  7. // Example 1: Convert a string argument to a number, limiting it to 100
  8. if (args.hasOwnProperty('number')) {
  9. const num = parseInt(args.number, 10);
  10. if (!isNaN(num) && num <= 100) {
  11. convertedArgs.number = num;
  12. } else {
  13. console.warn("Number argument must be a number between 0 and 100.");
  14. }
  15. }
  16. // Example 2: Convert a string argument to a boolean, with a default value
  17. if (args.flag) {
  18. convertedArgs.isValid = true;
  19. } else {
  20. convertedArgs.isValid = false; // Default value
  21. }
  22. // Example 3: Convert a string argument to a specific format
  23. if (args.name) {
  24. convertedArgs.formattedName = args.name.toUpperCase();
  25. }
  26. //Example 4: Convert an array of numbers to a single number (sum)
  27. if(args.numbers){
  28. const sum = args.numbers.reduce((acc, num) => acc + num, 0);
  29. convertedArgs.sum = sum;
  30. }
  31. return convertedArgs;
  32. }
  33. // Main execution
  34. const args = require('yargs').argv; //Using yargs for CLI argument parsing
  35. const converted = convertArgs(args);
  36. console.log(JSON.stringify(converted, null, 2)); //Output the converted arguments in JSON format

Add your comment