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