/**
* Handles array operations with graceful failure.
*
* @param {Array} arr The array to operate on.
* @param {function} operation The function to perform on the array.
* @param {function} errorHandler A function to handle errors. Takes error object as argument.
* @returns {Array|null} The result of the operation if successful, null if an error occurs.
*/
function safeArrayOperation(arr, operation, errorHandler) {
try {
// Check if the input is an array
if (!Array.isArray(arr)) {
errorHandler("Input must be an array");
return null;
}
// Check if the operation is a function
if (typeof operation !== 'function') {
errorHandler("Operation must be a function");
return null;
}
const result = operation(arr);
return result;
} catch (error) {
// Handle errors during the operation
errorHandler(error);
return null;
}
}
// Example usage (demonstrates error handling)
function exampleOperation(arr) {
// Simulate a potential error
if (arr.length === 0) {
throw new Error("Array is empty");
}
return arr.map(x => x * 2);
}
function myErrorHandler(error) {
console.error("Error occurred:", error.message);
}
// Test cases
const myArray = [1, 2, 3, 4, 5];
const result1 = safeArrayOperation(myArray, exampleOperation, myErrorHandler);
console.log("Result 1:", result1); // Output: [2, 4, 6, 8, 10]
const emptyArray = [];
const result2 = safeArrayOperation(emptyArray, exampleOperation, myErrorHandler);
console.log("Result 2:", result2); // Output: null
const notAnArray = "hello";
const result3 = safeArrayOperation(notAnArray, exampleOperation, myErrorHandler);
console.log("Result 3:", result3); // Output: null
const invalidOperation = "not a function";
const result4 = safeArrayOperation(myArray, invalidOperation, myErrorHandler);
console.log("Result 4:", result4); // Output: null
Add your comment