Skip to content

Instantly share code, notes, and snippets.

@mrw34

mrw34/index.js

Last active Apr 11, 2016
Embed
What would you like to do?
Stable JavaScript Object hash function for Node.js
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');
}
@mrw34

This comment has been minimized.

Copy link
Owner Author

@mrw34 mrw34 commented Apr 11, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment