const fs = require('fs');
const path = require('path');
/**
* Decodes dataset input based on a configuration file.
* @param {string} inputData The raw dataset input.
* @param {string} configPath The path to the configuration file.
* @returns {any} The decoded dataset, or null if decoding fails.
*/
function decodeDataset(inputData, configPath) {
try {
// Read the configuration file.
const config = require(path.resolve(configPath));
// Validate configuration
if (!config || typeof config.schema !== 'object' || !config.schema.type) {
console.error("Invalid configuration file format.");
return null;
}
const schemaType = config.schema.type;
switch (schemaType) {
case 'json':
try {
return JSON.parse(inputData);
} catch (error) {
console.error("JSON parsing error:", error);
return null;
}
case 'csv':
try {
const lines = inputData.split('\n');
const headers = lines[0].split(',');
const data = [];
for (let i = 1; i < lines.length; i++) {
const values = lines[i].split(',');
if (values.length !== headers.length) {
console.warn(`Skipping row ${i + 1} due to mismatched column count.`);
continue;
}
const row = {};
for (let j = 0; j < headers.length; j++) {
row[headers[j].trim()] = values[j].trim();
}
data.push(row);
}
return data;
} catch (error) {
console.error("CSV parsing error:", error);
return null;
}
case 'yaml':
try {
return require('yaml').parse(inputData);
} catch (error) {
console.error("YAML parsing error:", error);
return null;
}
default:
console.error("Unsupported schema type:", schemaType);
return null;
}
} catch (error) {
console.error("Error during decoding:", error);
return null;
}
}
module.exports = decodeDataset;
Add your comment