In Java, a hashCode algorithm can be used to calculate the hash value of a string. Today, a friend suddenly asked me if I can calculate hashCode in js, and the requirement is the same as the hashCode calculation result of Java.
I have never understood the algorithm of Java's hashCode until now, but it probably won't be too difficult. So I wrote this code in Java for testing:
Running result: 899755
Press the Ctrl key and click the hashCode method name to follow up and look at its algorithm. I found that it is a few simple code sentences, as shown below:
The code copy is as follows:
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;
}
Now, it should be OK if you simply port it to JS. So I wrote the following JS code:
The code copy is as follows:
<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, the same as the java calculation result. I thought this would be done, and then I thought about finding a string to test it out:
"Shenyang, Shenyang", the result of running in JAVA is: 1062711668, but it becomes: 26832515444 in js.
I'm so terrible, there's a problem with this just one try! After thinking for a moment, I suddenly realized that the length of int in Java seems to be about 2.1 billion, and there is no such restriction in JS. The problem should be here, so I made some modifications to the previous method:
The code copy is as follows:
<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! The mission is done. No technical content, a little summary
Updated on 2013-02-19, the above one is relatively inefficient and will be dispelled when the content is very long. The following code is the optimized code:
The code copy is as follows:
<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 overflows to take the module
}
/*var t = -2147483648 * 2;
while (h > 2147483647) {
h += t
}*/
return h;
}
alert(hashCode('C# how to execute N threads in concurrently at the same time, the rest are implemented in the queue')); //1107373715
</script>