/**
* Cleans data collections for manual execution with a dry-run mode.
*
* @param {object} collections An object containing data collections. Each key is a collection name,
* and the value is an array of data objects.
* @param {object} options Configuration options.
* @param {boolean} options.dryRun If true, only logs the changes without modifying the collections. Defaults to false.
*/
function cleanData(collections, options = {}) {
const { dryRun = false } = options;
for (const collectionName in collections) {
if (collections.hasOwnProperty(collectionName)) {
const collection = collections[collectionName];
if (!Array.isArray(collection)) {
console.warn(`Collection "${collectionName}" is not an array. Skipping.`);
continue;
}
const cleanedCollection = [];
for (const item of collection) {
if (typeof item !== 'object' || item === null) {
console.warn(`Skipping invalid item in collection "${collectionName}":`, item);
continue;
}
const cleanedItem = {};
for (const key in item) {
if (item.hasOwnProperty(key)) {
let value = item[key];
if (value === null || value === undefined) {
cleanedItem[key] = null; // Handle null/undefined values
} else if (typeof value === 'string') {
value = value.trim(); // Trim whitespace from strings
cleanedItem[key] = value;
} else if (typeof value === 'number') {
cleanedItem[key] = Number(value); // Convert to number if possible
} else if (Array.isArray(value)) {
cleanedItem[key] = value.map(item2 => (typeof item2 === 'string' ? item2.trim() : item2)); //trim array elements
} else if (typeof value === 'object' && value !== null) {
cleanedItem[key] = cleanData({[key]: value}, options).data[key]; //recursive call for nested objects
}
else {
cleanedItem[key] = value;
}
}
}
cleanedCollection.push(cleanedItem);
}
if (dryRun) {
console.log(`Dry Run: Cleaning collection "${collectionName}"`);
console.log("Changes:");
console.log(JSON.stringify(cleanedCollection, null, 2));
} else {
console.log(`Cleaning collection "${collectionName}"`);
collections[collectionName] = cleanedCollection;
}
}
}
}
Add your comment