1. function decodeConfig(configString) {
  2. const config = {};
  3. if (typeof configString !== 'string') {
  4. throw new Error('Config string must be a string.');
  5. }
  6. const lines = configString.trim().split('\n');
  7. for (const line of lines) {
  8. const trimmedLine = line.trim();
  9. if (trimmedLine === '') {
  10. continue; // Skip empty lines
  11. }
  12. const parts = trimmedLine.split('=');
  13. if (parts.length !== 2) {
  14. throw new Error(`Invalid config line format: ${trimmedLine}. Expected 'key=value'.`);
  15. }
  16. const key = trimmedLine.split('=')[0].trim();
  17. const value = trimmedLine.split('=')[1].trim();
  18. if (!key) {
  19. throw new Error(`Config key cannot be empty in line: ${trimmedLine}`);
  20. }
  21. if (!value) {
  22. throw new Error(`Config value cannot be empty in line: ${trimmedLine}`);
  23. }
  24. // Defensive checks and type conversions
  25. if (value.toLowerCase() === 'true') {
  26. config[key] = true;
  27. } else if (value.toLowerCase() === 'false') {
  28. config[key] = false;
  29. } else if (!isNaN(value)) {
  30. config[key] = Number(value); // Attempt to parse as number
  31. } else {
  32. config[key] = value; // Treat as string
  33. }
  34. }
  35. return config;
  36. }

Add your comment