Skip to content

Commit

Permalink
Fix scala-js#149: Implement String.hashCode()
Browse files Browse the repository at this point in the history
  • Loading branch information
gzm0 committed Jan 27, 2014
1 parent c66bbbc commit 3f59f11
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
21 changes: 20 additions & 1 deletion corejslib/scalajsenv.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,27 @@ var ScalaJS = {
objectHashCode: function(instance) {
if (ScalaJS.isScalaJSObject(instance))
return instance.hashCode__I();
else
else if (typeof(instance) === "string") {
// calculate hash of String as specified by JavaDoc
var n = instance.length;
var res = 0;
var mul = 1; // holds pow(31, n-i-1)
// multiplications with `mul` do never overflow the 52 bits of precision:
// - we truncate `mul` to 32 bits on each operation
// - 31 has 5 significant bits only
// - s[i] has 16 significant bits max
// 32 + max(5, 16) = 48 < 52 => no overflow
for (var i = n-1; i >= 0; --i) {
// calculate s[i] * pow(31, n-i-1)
res = res + (instance.charCodeAt(i) * mul | 0) | 0
// update mul for next iteration
mul = mul * 31 | 0
}

return res;
} else {
return 42; // TODO
}
},

comparableCompareTo: function(instance, rhs) {
Expand Down
12 changes: 9 additions & 3 deletions test/src/test/scala/scala/scalajs/test/javalib/StringTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -113,17 +113,23 @@ object StringTest extends JasmineTest {

it("should respond to `split`") {
expect("Scala.js".split("a")).toEqual(js.Array("Sc", "l", ".js"))

}

it("should respond to `split` with char as argument") {
expect("Scala.js".split('.')).toEqual(js.Array("Scala","js"))
}

it("should respond to `toCharArray`") {
expect("Scala.js".toCharArray()(5)).toEqual('.')
}

it("should respond to `hashCode`") {
expect("a`jkxzcbfaslkjfbkj,289oinkasdf".hashCode()).toEqual(-1395193631)
expect("-34".hashCode()).toEqual(44878)
expect("".hashCode()).toEqual(0)
}

it("should provide `format`") {
expect(String.format("%d", new Integer(5))).toEqual("5")
expect(String.format("%05d", new Integer(5))).toEqual("00005")
Expand Down

0 comments on commit 3f59f11

Please sign in to comment.