Created
February 15, 2021 18:16
-
-
Save rgpower/a0801d87caf8ba51639ad82edcac2d11 to your computer and use it in GitHub Desktop.
JSON digest for comparing parsed json payloads
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| goog.provide('json.digest'); | |
| goog.require('goog.array'); | |
| goog.require('goog.crypt'); | |
| goog.require('goog.crypt.Hash'); | |
| goog.require('goog.crypt.Sha1'); | |
| goog.require('goog.object'); | |
| /** | |
| * @param {Object} item | |
| * @param {goog.crypt.Hash=} opt_hash | |
| * @return {string} | |
| */ | |
| json.digest = function(item, opt_hash) { | |
| return /** @type {string} */ (json.digest_(item, opt_hash)); | |
| }; | |
| /** | |
| * @private | |
| * @param {Object} item | |
| * @param {goog.crypt.Hash=} opt_hash | |
| * @param {boolean=} opt_update_only | |
| * @return {?string} | |
| */ | |
| json.digest_ = function(item, opt_hash, opt_update_only) { | |
| var hash = opt_hash instanceof goog.crypt.Hash ? opt_hash : new goog.crypt.Sha1(); | |
| /* | |
| * Keys need to be ordered to guarantee digest will be the same | |
| * for every call of the same keys | |
| */ | |
| var sortedKeys = goog.object.getKeys(item); | |
| goog.array.sort(sortedKeys); | |
| goog.array.forEach(sortedKeys, function(key) { | |
| hash.update(key + ':'); | |
| var val = goog.object.get(item, key); | |
| if (goog.isArrayLike(val)) { | |
| json.digest_(goog.array.toObject(val, function(el, i) { | |
| return i + '' /* keys need to be string type */; | |
| }, this), hash, true); | |
| } | |
| else if (goog.isObject(val)) { | |
| json.digest_(val, hash, true); | |
| } else { | |
| hash.update(val + '' /* poor man's cast for undefined/null etc */); | |
| } | |
| }); | |
| if (opt_update_only) { | |
| return null; | |
| } | |
| return goog.crypt.byteArrayToHex(hash.digest()); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment