Created
November 18, 2014 16:12
-
-
Save Trindaz/7f3cff734ca247609a7b to your computer and use it in GitHub Desktop.
A deterministic, circular reference safe hash function for javascript objects
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
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