1. #!/usr/bin/env node
  2. const process = require('process');
  3. /**
  4. * Formats command-line options with basic sanity checks.
  5. * @param {object} options - The parsed command-line options object.
  6. * @returns {string} - Formatted output string.
  7. */
  8. function formatOptions(options) {
  9. let output = '';
  10. // Basic sanity checks
  11. if (!options.name) {
  12. return "Error: --name is required.";
  13. }
  14. if (typeof options.age !== 'number' || options.age < 0) {
  15. return "Error: --age must be a non-negative number.";
  16. }
  17. if (options.verbose !== undefined && typeof options.verbose !== 'boolean') {
  18. return "Error: --verbose must be a boolean value.";
  19. }
  20. output += `Name: ${options.name}\n`;
  21. output += `Age: ${options.age}\n`;
  22. if (options.verbose) {
  23. output += `Verbose mode enabled.\n`;
  24. }
  25. if (options.email) {
  26. output += `Email: ${options.email}\n`;
  27. }
  28. if (options.id) {
  29. output += `ID: ${options.id}\n`;
  30. }
  31. return output;
  32. }
  33. // Example usage (simulating command-line parsing)
  34. const parsedArgs = {
  35. name: 'John Doe',
  36. age: 30,
  37. verbose: true,
  38. email: 'john.doe@example.com',
  39. id: '12345'
  40. };
  41. const formattedOutput = formatOptions(parsedArgs);
  42. console.log(formattedOutput);
  43. //Another example with error
  44. const parsedArgsError = {
  45. name: '',
  46. age: -5
  47. };
  48. const formattedOutputError = formatOptions(parsedArgsError);
  49. console.log(formattedOutputError);

Add your comment