Last active
April 11, 2016 20:13
-
-
Save mrw34/6fd5b9b5a5437e351c02 to your computer and use it in GitHub Desktop.
Stable JavaScript Object hash function for Node.js
This file contains 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
function hash(object, algorithm, encoding) { | |
var h = require('crypto').createHash(algorithm || 'md5'); | |
(function update(v, k) { | |
if (k !== undefined) { | |
h.update(JSON.stringify(k)); | |
} | |
if (v && v.constructor === Array) { | |
v.forEach(function(value) { | |
update(h, value); | |
}); | |
} else if (v && v.constructor === Object) { | |
var keys = Object.keys(v); | |
keys.sort(); | |
keys.forEach(function(key) { | |
update(h, v[key], key); | |
}); | |
} else { | |
h.update(JSON.stringify(v)); | |
} | |
})(object); | |
return h.digest(encoding || 'hex'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also https://github.com/substack/json-stable-stringify