sjehuda / Hash Code

Published:

Version: 1.0.0+7bb79f7 updated

Summary: Javascript implementation of Java’s String.hashCode() method

Homepage: https://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/

Copyright: 2010, wes

License: MIT

Usage:

String.prototype.hashCode()

Example:

"some string".hashCode() // 1395333309

Javascript implementation of Java’s String.hashCode() method

13 May, 2010 in java / javascript tagged hashcode / javascript / prototype by wex

Here is a direct replacement for Java’s String.hashCode() method implemented in Javascript.

I wrote this function to fulfill a requirement at work. Apparently, the back-end engineers thought hashCode() was a standard function. One of the hurdles for this project was not only figuring out how to translate the mathematical formula used in Java to generate hashCode()’s but also how to force Javascript to use 32bit integer math (no small feat).

Fortunately, I discovered that Javascript supports bitwise operators which are constrained to 32bit integer math.

So here’s the resulting String prototype in Javascript. With this prototype you can simply call .hashCode() on any string, i.e. "some string".hashCode(), and receive a numerical hash code (more specifically, a Java equivalent) such as 1395333309.

String.prototype.hashCode = function(){
    var hash = 0;
    if (this.length == 0) return hash;
    for (i = 0; i < this.length; i++) {
        char = this.charCodeAt(i);
        hash = ((hash<<5)-hash)+char;
        // Convert to 32bit integer
        hash = hash & hash;
    }
    return hash;
}

Source: werxltd.com (manwe.io)

Manwe Security Consulting

Werx Limited

Rating: 0