0

I'm working on a multi platform app and I've finished the database and the web version. To check a code on the web version I get a hashed version from the database and compare the two. I use this javascript code to hash (I found this on another question):

hashCode = function(s){
  return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);              
}

Now I need to do the same in my android app, but I don't know how to make a function that outputs the same in java or kotlin. Does anyone know how to do this or have an other cross-platform vanilla solution?

Thanks in advance.

Edit: I'm very new to kotlin/java so I only know what I can find online and what I know about other languages. I tried to remove as much errors as possible but some things I just don't know, it still gives errors:

   fun go (a: Int, b: String): Int {
    var a = ((a shl 5) - a) + Character.codePointAt(b,0);
    return a and a
} // this part doesn't give any errors now.


fun hashCode(s: String): String {
    return s.split("").reduce(go(a,b)) // I don't know what to pass as parameters + reduce gives an error
}
Community
  • 1
  • 1

1 Answers1

0

If you concerned with getting the hash code, and not replicating the javascript function into kotlin yourself, I suggest you can use this one liner.

val s:String = "aaaa";
println(s.hashCode());

Output is 2986048

I checked with javascript version, it is same.

Here is the documentation for hashCode in kotlin

open fun hashCode(): Int (source)

Returns a hash code value for the object. The general contract of hashCode is:

Whenever it is invoked on the same object more than once, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.

If two objects are equal according to the equals() method, then calling the hashCode method on each of the two objects must produce the same integer result.

Community
  • 1
  • 1
Santosh
  • 1,871
  • 1
  • 19
  • 36
  • Woah dude, it works! Is the javascript version so basic and common kotlin has it built in as hashCode()? – Robin van der Noord May 21 '17 at 15:22
  • @RobinvanderNoord I think hashing functions are basic, and every language should have some kind of implementation. It always better to check the documentation before implementing it ourselves though :-) – Santosh May 21 '17 at 15:26