Hash Code

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

Acest script nu ar trebui instalat direct. Aceasta este o bibliotecă pentru alte scripturi care este inclusă prin directiva meta a // @require https://update.greasyfork.org/scripts/466055/1189121/Hash%20Code.js

Autor
schimon
Versiune
1.0.0
Creat
11-05-2023
Actualizat
11-05-2023
Licență
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