1. /**
  2. * Hashes an array of objects with defensive checks.
  3. *
  4. * @param {Array<Object>} data - The array of objects to hash.
  5. * @param {string} hashAlgorithm - The hashing algorithm to use (e.g., 'sha256', 'md5'). Defaults to 'sha256'.
  6. * @returns {Array<Object>} - The array with added hash values, or an empty array if input is invalid.
  7. */
  8. function hashBatch(data, hashAlgorithm = 'sha256') {
  9. if (!Array.isArray(data)) {
  10. console.error("Input must be an array.");
  11. return [];
  12. }
  13. if (data.length === 0) {
  14. return []; // Return empty array if input is empty
  15. }
  16. if (typeof hashAlgorithm !== 'string') {
  17. console.error("Hash algorithm must be a string.");
  18. return [];
  19. }
  20. const hashedData = data.map(item => {
  21. if (typeof item !== 'object' || item === null) {
  22. console.warn("Skipping non-object item:", item);
  23. return { ...item, hash: null }; // Add null hash for non-object items.
  24. }
  25. if (typeof item.data !== 'string') {
  26. console.warn("Skipping item with invalid 'data' property:", item);
  27. return { ...item, hash: null }; // Add null hash for items with invalid data
  28. }
  29. try {
  30. const hash = crypto[hashAlgorithm](item.data).toString(); //Use built in crypto for hashing
  31. return { ...item, hash: hash };
  32. } catch (error) {
  33. console.error(`Error hashing item: ${item}. Error: ${error}`);
  34. return { ...item, hash: null }; // Return null hash on error
  35. }
  36. });
  37. return hashedData;
  38. }
  39. //Example Usage (not part of the function)
  40. //const data = [{ data: 'hello' }, { data: 'world' }, 123, {data: 123}];
  41. //const hashedData = hashBatch(data, 'sha256');
  42. //console.log(hashedData);

Add your comment