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.
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;
}