/**
* Hashes an array of objects with defensive checks.
*
* @param {Array<Object>} data - The array of objects to hash.
* @param {string} hashAlgorithm - The hashing algorithm to use (e.g., 'sha256', 'md5'). Defaults to 'sha256'.
* @returns {Array<Object>} - The array with added hash values, or an empty array if input is invalid.
*/
function hashBatch(data, hashAlgorithm = 'sha256') {
if (!Array.isArray(data)) {
console.error("Input must be an array.");
return [];
}
if (data.length === 0) {
return []; // Return empty array if input is empty
}
if (typeof hashAlgorithm !== 'string') {
console.error("Hash algorithm must be a string.");
return [];
}
const hashedData = data.map(item => {
if (typeof item !== 'object' || item === null) {
console.warn("Skipping non-object item:", item);
return { ...item, hash: null }; // Add null hash for non-object items.
}
if (typeof item.data !== 'string') {
console.warn("Skipping item with invalid 'data' property:", item);
return { ...item, hash: null }; // Add null hash for items with invalid data
}
try {
const hash = crypto[hashAlgorithm](item.data).toString(); //Use built in crypto for hashing
return { ...item, hash: hash };
} catch (error) {
console.error(`Error hashing item: ${item}. Error: ${error}`);
return { ...item, hash: null }; // Return null hash on error
}
});
return hashedData;
}
//Example Usage (not part of the function)
//const data = [{ data: 'hello' }, { data: 'world' }, 123, {data: 123}];
//const hashedData = hashBatch(data, 'sha256');
//console.log(hashedData);
Add your comment