Skip to content

Instantly share code, notes, and snippets.

@blakev
Created August 18, 2014 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blakev/f6c1fc1b59fb318c0e84 to your computer and use it in GitHub Desktop.
Save blakev/f6c1fc1b59fb318c0e84 to your computer and use it in GitHub Desktop.
JavaScript JSON Hashing
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