Skip to content

Instantly share code, notes, and snippets.

@Trindaz
Created November 18, 2014 16:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Trindaz/7f3cff734ca247609a7b to your computer and use it in GitHub Desktop.
Save Trindaz/7f3cff734ca247609a7b to your computer and use it in GitHub Desktop.
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