/**
* Asserts conditions on lists and logs errors if conditions are not met.
*
* @param {Array} list The list to validate.
* @param {function} condition A function that takes a list and returns a boolean.
* @param {string} message The error message to log if the condition fails.
*/
function assertListCondition(list, condition, message) {
if (!Array.isArray(list)) {
console.error(`Error: Input must be an array. ${message}`);
return;
}
if (typeof condition !== 'function') {
console.error(`Error: Condition must be a function. ${message}`);
return;
}
if (!condition(list)) {
console.error(`Assertion failed: ${message}. List:`, list);
}
}
/**
* Example usage:
*/
//Example 1: Check if all elements are positive numbers
function allPositiveNumbers(list) {
if (!Array.isArray(list)) return false;
return list.every(item => typeof item === 'number' && item > 0);
}
assertListCondition([1, 2, 3, 4, 5], allPositiveNumbers, "All elements must be positive numbers.");
assertListCondition([1, -2, 3, 4, 5], allPositiveNumbers, "All elements must be positive numbers.");
assertListCondition([1, 2, 'a', 4, 5], allPositiveNumbers, "All elements must be positive numbers.");
//Example 2: Check if list is sorted in ascending order
function isSortedAscending(list) {
if (!Array.isArray(list)) return false;
for (let i = 0; i < list.length - 1; i++) {
if (list[i] > list[i + 1]) {
return false;
}
}
return true;
}
assertListCondition([1, 2, 3, 4, 5], isSortedAscending, "List must be sorted in ascending order.");
assertListCondition([1, 2, 5, 4, 3], isSortedAscending, "List must be sorted in ascending order.");
assertListCondition([], isSortedAscending, "List must be sorted in ascending order.");
Add your comment