1. /**
  2. * Cleans data collections for manual execution with a dry-run mode.
  3. *
  4. * @param {object} collections An object containing data collections. Each key is a collection name,
  5. * and the value is an array of data objects.
  6. * @param {object} options Configuration options.
  7. * @param {boolean} options.dryRun If true, only logs the changes without modifying the collections. Defaults to false.
  8. */
  9. function cleanData(collections, options = {}) {
  10. const { dryRun = false } = options;
  11. for (const collectionName in collections) {
  12. if (collections.hasOwnProperty(collectionName)) {
  13. const collection = collections[collectionName];
  14. if (!Array.isArray(collection)) {
  15. console.warn(`Collection "${collectionName}" is not an array. Skipping.`);
  16. continue;
  17. }
  18. const cleanedCollection = [];
  19. for (const item of collection) {
  20. if (typeof item !== 'object' || item === null) {
  21. console.warn(`Skipping invalid item in collection "${collectionName}":`, item);
  22. continue;
  23. }
  24. const cleanedItem = {};
  25. for (const key in item) {
  26. if (item.hasOwnProperty(key)) {
  27. let value = item[key];
  28. if (value === null || value === undefined) {
  29. cleanedItem[key] = null; // Handle null/undefined values
  30. } else if (typeof value === 'string') {
  31. value = value.trim(); // Trim whitespace from strings
  32. cleanedItem[key] = value;
  33. } else if (typeof value === 'number') {
  34. cleanedItem[key] = Number(value); // Convert to number if possible
  35. } else if (Array.isArray(value)) {
  36. cleanedItem[key] = value.map(item2 => (typeof item2 === 'string' ? item2.trim() : item2)); //trim array elements
  37. } else if (typeof value === 'object' && value !== null) {
  38. cleanedItem[key] = cleanData({[key]: value}, options).data[key]; //recursive call for nested objects
  39. }
  40. else {
  41. cleanedItem[key] = value;
  42. }
  43. }
  44. }
  45. cleanedCollection.push(cleanedItem);
  46. }
  47. if (dryRun) {
  48. console.log(`Dry Run: Cleaning collection "${collectionName}"`);
  49. console.log("Changes:");
  50. console.log(JSON.stringify(cleanedCollection, null, 2));
  51. } else {
  52. console.log(`Cleaning collection "${collectionName}"`);
  53. collections[collectionName] = cleanedCollection;
  54. }
  55. }
  56. }
  57. }

Add your comment