Skip to content

Instantly share code, notes, and snippets.

@gabrieldewes
Last active February 9, 2017 19:13
Show Gist options
  • Save gabrieldewes/8d494bd3401f03ec443fc7b814f0638e to your computer and use it in GitHub Desktop.
Save gabrieldewes/8d494bd3401f03ec443fc7b814f0638e to your computer and use it in GitHub Desktop.
Simple Java Script object hashing
/**
* @description Simple hashing for JS objects
* @author Gabriel Dewes at 9 nov, 2016
*/
Object.prototype.hashify = function(obj, len) {
obj = obj || this;
len = len || 2;
var i, j, r=[];
for (i=0; i<len; i++) {
r.push(i*268803292);
}
obj = stringify(obj);
for (i=0; i<obj.length; i++) {
for (j=0; j<r.length; j++) {
r[j] = (r[j] << 13) - (r[j] >> 19);
r[j] += obj.charCodeAt(i) << (r[j] % 24);
r[j] = r[j] & r[j];
}
}
for (i=0; i<r.length; i++) {
r[i] = r[i].toHex();
}
return r.join('');
};
function stringify(obj) {
var i, r;
if (obj === null) return 'null';
if (obj === true) return 'true';
if (obj === false) return 'false';
i = typeof obj;
if (i === 'string') return 'string:'+ obj.replace(/([\\\\;])/g,'\\$1');
if (i === 'number') return 'number:'+ obj.toString().replace(/([\\\\;])/g,'\\$1');
if (obj instanceof Date) return 'date:'+ obj;
if (obj instanceof Function) return 'function:'+ obj.toString().replace(/([\\\\;])/g,'\\$1');
if (obj instanceof Array) {
r=[];
for (i=0; i<obj.length; i++) {
r.push(stringify(obj[i]));
}
return 'array:'+ r.join(',');
}
r=[];
for (i in obj) {
r.push(i +':'+ stringify(obj[i]));
}
return 'object:'+ r[0];
};
Number.prototype.toHex = function () {
var ret = ((this < 0 ? 0x8 : 0) +
((this >> 28) & 0x7)).toString(16) +
(this & 0xfffffff).toString(16);
while (ret.length < 8) ret = '0'+ ret;
return ret;
};
var a = [
{g:1, a:'2', b:[3]},
10,
['g',4,'b','r',1,'e','l'],
"gabriel",
new Date(),
function(){return true;},
50.34,
null,
true,
false
],
console.log(a.hashify() === hashify(a));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment