Skip to content

Instantly share code, notes, and snippets.

@Trindaz

Trindaz/hash.js

Created Nov 18, 2014
Embed
What would you like to do?
A deterministic, circular reference safe hash function for javascript objects
function hash(obj) {
var cache = [];
function sanitize(obj) {
if (obj === null) { return obj; }
if (['undefined', 'boolean', 'number', 'string', 'function'].indexOf(typeof(obj)) >= 0) { return obj; }
if (typeof(obj)==='object') {
var keys = Object.keys(obj).sort(),
values = [];
for(var i=0; i<keys.length; i++){
var value = obj[keys[i]];
if (cache.indexOf(value) === -1) {
values.push(sanitize(value));
cache.push(value);
} else {
values.push('[ Previously hashed object ]');
}
}
return [keys, values];
}
}
return JSON.stringify(sanitize(obj));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.