/**
* Array Assertions for CLI
*/
const assertArray = (arr, message, condition) => {
if (!Array.isArray(arr)) {
console.error(`Assertion failed: ${message}. Expected an array.`);
return false;
}
if (!condition(arr)) {
console.error(`Assertion failed: ${message}.`);
return false;
}
return true;
};
/**
* Checks if an array is empty
* @param {Array} arr The array to check
* @param {string} message The error message if the assertion fails
* @returns {boolean} True if the array is empty, false otherwise.
*/
const isEmpty = (arr, message) => {
return assertArray(arr, message, (a) => a.length === 0);
};
/**
* Checks if an array contains only numbers
* @param {Array} arr The array to check
* @param {string} message The error message if the assertion fails
* @returns {boolean} True if the array contains only numbers, false otherwise.
*/
const allNumbers = (arr, message) => {
return assertArray(arr, message, (a) => typeof a === 'number' && !isNaN(a));
};
/**
* Checks if an array contains unique elements
* @param {Array} arr The array to check
* @param {string} message The error message if the assertion fails
* @returns {boolean} True if the array contains unique elements, false otherwise.
*/
const areUnique = (arr, message) => {
const seen = new Set();
return assertArray(arr, message, (a) => {
if (seen.has(a)) {
console.error(`Assertion failed: ${message}. Array contains duplicate elements.`);
return false;
}
seen.add(a);
return true;
});
};
/**
* Checks if an array is sorted in ascending order
* @param {Array} arr The array to check
* @param {string} message The error message if the assertion fails
* @returns {boolean} True if the array is sorted, false otherwise.
*/
const isSortedAscending = (arr, message) => {
return assertArray(arr, message, (a, b) => a <= b);
};
/**
* Checks if an array is sorted in descending order
* @param {Array} arr The array to check
* @param {string} message The error message if the assertion fails
* @returns {boolean} True if the array is sorted, false otherwise.
*/
const isSortedDescending = (arr, message) => {
return assertArray(arr, message, (a, b) => a >= b);
};
/**
* Checks if an array contains a specific value.
* @param {Array} arr The array to check.
* @param {any} value The value to search for.
* @param {string} message The error message if the assertion fails.
* @returns {boolean} True if the array contains the value, false otherwise.
*/
const containsValue = (arr, value, message) => {
return assertArray(arr, message, (a) => a === value);
};
/**
* Checks if an array has a specific length.
* @param {Array} arr The array to check.
* @param {number} expectedLength The expected length of the array.
* @param {string} message The error message if the assertion fails.
* @returns {boolean} True if the array has the expected length, false otherwise.
*/
const hasLength = (arr, expectedLength, message) => {
return assertArray(arr, message, (a) => a.length === expectedLength);
};
Add your comment