hash.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * utilities for hashing config objects.
  3. * basically iteratively updates hash with a JSON-like format
  4. */
  5. 'use strict';
  6. exports.__esModule = true;
  7. const createHash = require('crypto').createHash;
  8. const stringify = JSON.stringify;
  9. function hashify(value, hash) {
  10. if (!hash) hash = createHash('sha256');
  11. if (Array.isArray(value)) {
  12. hashArray(value, hash);
  13. } else if (value instanceof Object) {
  14. hashObject(value, hash);
  15. } else {
  16. hash.update(stringify(value) || 'undefined');
  17. }
  18. return hash;
  19. }
  20. exports.default = hashify;
  21. function hashArray(array, hash) {
  22. if (!hash) hash = createHash('sha256');
  23. hash.update('[');
  24. for (let i = 0; i < array.length; i++) {
  25. hashify(array[i], hash);
  26. hash.update(',');
  27. }
  28. hash.update(']');
  29. return hash;
  30. }
  31. hashify.array = hashArray;
  32. exports.hashArray = hashArray;
  33. function hashObject(object, hash) {
  34. if (!hash) hash = createHash('sha256');
  35. hash.update('{');
  36. Object.keys(object).sort().forEach(key => {
  37. hash.update(stringify(key));
  38. hash.update(':');
  39. hashify(object[key], hash);
  40. hash.update(',');
  41. });
  42. hash.update('}');
  43. return hash;
  44. }
  45. hashify.object = hashObject;
  46. exports.hashObject = hashObject;