Created
August 18, 2014 03:16
-
-
Save blakev/f6c1fc1b59fb318c0e84 to your computer and use it in GitHub Desktop.
JavaScript JSON Hashing
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
var _ = require('underscore'); | |
function hash(data) { | |
function innerHash(data) { | |
var hashStr = ''; | |
if(_.isArray(data)) { | |
_.each(data, function(e) { | |
hashStr += innerHash(e) + ',' | |
}) | |
} else | |
if(_.isObject(data)) { | |
_.each(_.pairs(data), function(p) { | |
hashStr += p[0].toString() + '::' + innerHash(p[1]) | |
}) | |
} else | |
return data.toString(); | |
return hashStr; | |
} | |
var h = innerHash(data), | |
index = h.length, | |
build = 0; | |
_.toArray(innerHash(data)).forEach(function(x) { | |
build += x.charCodeAt(0) * index-- | |
}) | |
return build.toString(32); | |
} | |
x = [ | |
123, | |
'blake 123', | |
[1,2,3,4,{b: 1}], | |
'blake', | |
'vandemerwe', | |
{a: 1, b: 2}, | |
{b: 1, a: 1}, | |
{a: 1, b: 1}, | |
{b: 2, a: 1}, | |
{a: 2, b: 1}, | |
{a:2, b:1}, | |
'this is a long sentence blah blah', | |
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum mollis, metus' | |
] | |
x.forEach(function(a) { | |
console.log(hash(a)); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment