Javascript to achieve JAVA compatible hashCode algorithm code sharing

  • 2020-03-30 03:43:13
  • OfStack

In Java, a hashCode algorithm can be used to calculate the hash value of a string. Today, a friend suddenly asked me if I could calculate hashCode in js, which requires the same result as hashCode in Java.

For Java hashCode, the algorithm has never been known before, but it should not be too difficult to guess, so now this code is written in Java to test:
Running result: 899755

Press the Ctrl key and click the name of the hashCode method to see its algorithm. It turns out to be a few simple lines of code, as shown below:


public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count; for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}

This is good, simple migration to js should be ok. So write the following JS code:


<script type="text/javascript">
function hashCode(str){
         var h = 0, off = 0;
         var len = str.length;
         for(var i = 0; i < len; i++){
             h = 31 * h + str.charCodeAt(off++);
         }
         return h;
     }
     alert(hashCode(' shenyang '));
   </script>

Running result: 899755

OK, same as the Java calculation. I thought that was it, and then I thought to find a random string of tests:

"Shenyang shenyang", running in JAVA results: 1062711668, but to js: 26832515444.

Crazy dizzy, this random try to have a problem! After a moment's thought, it suddenly occurred to me that the length of int in Java seems to be about 2.1 billion, and js has no such limit. That should be the problem, so I changed the method a little bit:


<script>
function hashCode(str){
         var h = 0, off = 0;
         var len = str.length;
         for(var i = 0; i < len; i++){
             h = 31 * h + str.charCodeAt(off++);
         }
     var t=-2147483648*2;
     while(h>2147483647){
       h+=t
     }
         return h;
     }
alert(hashCode(' Shenyang shenyang '));</script>

Test again! OK! And we're done. Nothing technical, a little summary
Update 2013-02-19, the above is inefficient, when the content is very long will be down, the following code is optimized after the code:


<script>
    function hashCode(str) {
        var h = 0;
        var len = str.length;
        var t = 2147483648;
        for (var i = 0; i < len; i++) {
            h = 31 * h + str.charCodeAt(i);
            if(h > 2147483647) h %= t;//Java int overflow takes the module
        }
        /*var t = -2147483648 * 2;
        while (h > 2147483647) {
            h += t
        }*/
        return h;
    }
    alert(hashCode('C# At the same time N Three threads execute concurrently , How is the rest implemented in the queue ')); //1107373715
</script>


Related articles: