Hash Code

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

אין להתקין סקריפט זה ישירות. זוהי ספריה עבור סקריפטים אחרים // @require https://update.greasyfork.org/scripts/466055/1189121/Hash%20Code.js

יוצר
schimon
גרסה
1.0.0
נוצר
11-05-2023
עודכן
11-05-2023
רישיון
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