function decodeConfig(configString) {
const config = {};
if (typeof configString !== 'string') {
throw new Error('Config string must be a string.');
}
const lines = configString.trim().split('\n');
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine === '') {
continue; // Skip empty lines
}
const parts = trimmedLine.split('=');
if (parts.length !== 2) {
throw new Error(`Invalid config line format: ${trimmedLine}. Expected 'key=value'.`);
}
const key = trimmedLine.split('=')[0].trim();
const value = trimmedLine.split('=')[1].trim();
if (!key) {
throw new Error(`Config key cannot be empty in line: ${trimmedLine}`);
}
if (!value) {
throw new Error(`Config value cannot be empty in line: ${trimmedLine}`);
}
// Defensive checks and type conversions
if (value.toLowerCase() === 'true') {
config[key] = true;
} else if (value.toLowerCase() === 'false') {
config[key] = false;
} else if (!isNaN(value)) {
config[key] = Number(value); // Attempt to parse as number
} else {
config[key] = value; // Treat as string
}
}
return config;
}
Add your comment