I need to convert strings to some form of hash. Is this possible in JavaScript?
I\'m not utilizing a server-side language so I can\'t do it that way.
Object.defineProperty(String.prototype, 'hashCode', {
value: function() {
var hash = 0, i, chr;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
});
Source: http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
I have combined the two solutions (users esmiralha and lordvlad) to get a function that should be faster for browsers that support the js function reduce() and still compatible with old browsers:
String.prototype.hashCode = function() {
if (Array.prototype.reduce) {
return this.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);
} else {
var hash = 0, i, chr, len;
if (this.length == 0) return hash;
for (i = 0, len = this.length; i < len; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
};
Example:
my_string = 'xyz';
my_string.hashCode();
This is a refined and better performing variant:
String.prototype.hashCode = function() {
var hash = 0, i = 0, len = this.length;
while ( i < len ) {
hash = ((hash << 5) - hash + this.charCodeAt(i++)) << 0;
}
return hash;
};
This matches Java's implementation of the standard object.hashCode()
Here is also one that returns only positive hashcodes:
String.prototype.hashcode = function() {
return (this.hashCode() + 2147483647) + 1;
};
And here is a matching one for Java that only returns positive hashcodes:
public static long hashcode(Object obj) {
return ((long) obj.hashCode()) + Integer.MAX_VALUE + 1l;
}
Enjoy!
Without prototype:
function hashCode(str) {
var hash = 0, i = 0, len = str.length;
while ( i < len ) {
hash = ((hash << 5) - hash + str.charCodeAt(i++)) << 0;
}
return hash;
}
If you want to avoid collisions you may want to use a secure hash like SHA-256. There are several JavaScript SHA-256 implementations.
I wrote tests to compare several hash implementations, see https://github.com/brillout/test-javascript-hash-implementations.
Or go to http://brillout.github.io/test-javascript-hash-implementations/, to run the tests.