Generate a Hash from string in Javascript

前端 未结 22 896
不知归路
不知归路 2020-11-22 03:34

I need to convert strings to some form of hash. Is this possible in JavaScript?

I\'m not utilizing a server-side language so I can\'t do it that way.

22条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 04:36

    This is a refined and better performing variant:

    String.prototype.hashCode = function() {
        var hash = 0, i = 0, len = this.length;
        while ( i < len ) {
            hash  = ((hash << 5) - hash + this.charCodeAt(i++)) << 0;
        }
        return hash;
    };
    

    This matches Java's implementation of the standard object.hashCode()

    Here is also one that returns only positive hashcodes:

    String.prototype.hashcode = function() {
        return (this.hashCode() + 2147483647) + 1;
    };
    

    And here is a matching one for Java that only returns positive hashcodes:

    public static long hashcode(Object obj) {
        return ((long) obj.hashCode()) + Integer.MAX_VALUE + 1l;
    }
    

    Enjoy!

    Without prototype:

    function hashCode(str) {
        var hash = 0, i = 0, len = str.length;
        while ( i < len ) {
            hash  = ((hash << 5) - hash + str.charCodeAt(i++)) << 0;
        }
        return hash;
    }
    

提交回复
热议问题