In Java, a hashcode algorithm can be used to compute the hash value of a string, today a friend suddenly asked me if I can calculate the hashcode in JS, the requirements and Java hashcode calculation results.
For Java Hashcode, has not known its algorithm until now, but guess should not be too difficult, so now Java wrote this code to test:
Run Result: 899755
Ctrl-click Hashcode method name follow up to see its algorithm, found is very simple code, as follows:
Copy Code code 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;
}
This is good, the simple transplant past to JS should be OK. So write the following JS code:
Copy Code code 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 = * H + str.charcodeat (off++);
}
return h;
}
Alert (hashcode (' Shenyang '));
</script>
Run Result: 899755
OK, the same as the Java calculation result. I thought it was done, and then I thought about finding a bunch of tests:
"Shenyang Shenyang Ah", in Java Run the result is: 1062711668, but to JS into: 26832515444.
Crazy dizzy, this casually try to have a problem! After thinking for a moment, suddenly think of the length of the Java int is about 2.1 billion, JS is not the limit. The problem should be here, and a little bit of the previous approach was changed:
Copy Code code as follows:
<script>
function Hashcode (str) {
var h = 0, off = 0;
var len = str.length;
for (var i = 0; i < len; i++) {
H = * H + str.charcodeat (off++);
}
var t=-2147483648*2;
while (h>2147483647) {
H+=t
}
return h;
}
Alert (Hashcode, Shenyang, Shenyang));</script>
Test again! Ok! Done. No technical content, a little summary
2013-02-19 Update, the above efficiency is low, when the content is very long time to drop, the following code is optimized code:
Copy Code code as follows:
<script>
function Hashcode (str) {
var h = 0;
var len = str.length;
var t = 2147483648;
for (var i = 0; i < len; i++) {
H = * H + str.charcodeat (i);
if (H > 2147483647) H%= t;//java int overflow takes modulo
}
/*var t =-2147483648 * 2;
while (H > 2147483647) {
H + t
}*/
return h;
}
Alert (Hashcode (' C # the same time n threads execute concurrently, the rest in the queue how to implement ')); 1107373715
</script>