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
作成日
2023/05/11
更新日
2023/05/11
ライセンス
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