1. /**
  2. * Filters dataset data based on sanity checks.
  3. * @param {Array<Object>} data - The dataset to filter.
  4. * @param {Array<Function>} sanityChecks - An array of sanity check functions. Each function should accept a data object and return a boolean.
  5. * @returns {Array<Object>} - A filtered array containing only data that passes all sanity checks.
  6. */
  7. function filterData(data, sanityChecks) {
  8. if (!Array.isArray(data)) {
  9. console.error("Data must be an array.");
  10. return [];
  11. }
  12. if (!Array.isArray(sanityChecks) || sanityChecks.length === 0) {
  13. console.warn("No sanity checks provided. Returning original data.");
  14. return data;
  15. }
  16. const filteredData = [];
  17. for (const item of data) {
  18. let passesAllChecks = true;
  19. for (const check of sanityChecks) {
  20. if (typeof check !== 'function') {
  21. console.error("Sanity checks must be functions.");
  22. return [];
  23. }
  24. if (!check(item)) {
  25. passesAllChecks = false;
  26. break; // No need to check further if one check fails
  27. }
  28. }
  29. if (passesAllChecks) {
  30. filteredData.push(item);
  31. }
  32. }
  33. return filteredData;
  34. }
  35. // Example sanity checks (can be extended)
  36. function checkNotNull(item) {
  37. return item !== null;
  38. }
  39. function checkString(item) {
  40. return typeof item === 'string';
  41. }
  42. function checkNumber(item) {
  43. return typeof item === 'number' && !isNaN(item);
  44. }
  45. function checkArray(item) {
  46. return Array.isArray(item);
  47. }

Add your comment