1. /**
  2. * Asserts conditions on lists and logs errors if conditions are not met.
  3. *
  4. * @param {Array} list The list to validate.
  5. * @param {function} condition A function that takes a list and returns a boolean.
  6. * @param {string} message The error message to log if the condition fails.
  7. */
  8. function assertListCondition(list, condition, message) {
  9. if (!Array.isArray(list)) {
  10. console.error(`Error: Input must be an array. ${message}`);
  11. return;
  12. }
  13. if (typeof condition !== 'function') {
  14. console.error(`Error: Condition must be a function. ${message}`);
  15. return;
  16. }
  17. if (!condition(list)) {
  18. console.error(`Assertion failed: ${message}. List:`, list);
  19. }
  20. }
  21. /**
  22. * Example usage:
  23. */
  24. //Example 1: Check if all elements are positive numbers
  25. function allPositiveNumbers(list) {
  26. if (!Array.isArray(list)) return false;
  27. return list.every(item => typeof item === 'number' && item > 0);
  28. }
  29. assertListCondition([1, 2, 3, 4, 5], allPositiveNumbers, "All elements must be positive numbers.");
  30. assertListCondition([1, -2, 3, 4, 5], allPositiveNumbers, "All elements must be positive numbers.");
  31. assertListCondition([1, 2, 'a', 4, 5], allPositiveNumbers, "All elements must be positive numbers.");
  32. //Example 2: Check if list is sorted in ascending order
  33. function isSortedAscending(list) {
  34. if (!Array.isArray(list)) return false;
  35. for (let i = 0; i < list.length - 1; i++) {
  36. if (list[i] > list[i + 1]) {
  37. return false;
  38. }
  39. }
  40. return true;
  41. }
  42. assertListCondition([1, 2, 3, 4, 5], isSortedAscending, "List must be sorted in ascending order.");
  43. assertListCondition([1, 2, 5, 4, 3], isSortedAscending, "List must be sorted in ascending order.");
  44. assertListCondition([], isSortedAscending, "List must be sorted in ascending order.");

Add your comment