Damn I've deleted the message somehow lol Do we h...
# javascript
e
Damn I've deleted the message somehow lol Do we have an
identityHashCode()
mechanism in K/JS?
a
No, because there is no API to get GC ID for an object. We can emulate it for sure, like this:
Copy code
var index = 0
val jsWeakHashMap = js("new WeakMap()")

fun identityHashCode(object: Any): Int =
  if (jsWeakHashMap.has(object))
     jsWeakHashMap.get(object)
  else 
     (index + 1).also { jsWeakHashMap.set(object, it) }
thank you color 1
e
I need to check how they've done it in Scala/JS https://github.com/scala-js/scala-js/issues/1027
Looks like they were using a counter, pretty much as you did there. I'll look on the up-to-date code
This is how it was done before they moved it to a code generation step https://github.com/scala-js/scala-js/commit/33792738f548047ac0057c28c0945b52dbb5550b#diff-c259eba87b2eb67bfc6b869e4[…]14eb57877f1c0dc6b5947c3d69L186 Look for
Copy code
// identityHashCode ---------------------------------------------------------
This is how they do it now with codegen https://github.com/scala-js/scala-js/blob/9f5cc98f7f8f1d93a07ca6592aea2e953488b062[…]c/main/scala/org/scalajs/linker/backend/emitter/CoreJSLib.scala
a
Mostly the same. They also use JS WeakMap
e
Yeah. When
WeakMap
is not available they use a magic field
Copy code
val hash = x.asInstanceOf[js.Dynamic].selectDynamic("$idHashCode$0")
Which, as far is can tell, is simply set to
nextIDHashCode()
And then there is also a fixed
42
when the class is sealed. I don't get that part.
a
Yeap. So, we can do the same. Actually, for the JS objects hashCode we do the same thing. https://github.com/JetBrains/kotlin/blob/8d1a90c23cbd4e04747e1e9815047bb54a987e83/libraries/stdlib/js/runtime/coreRuntime.kt#L44
e
So, in K/JS the hash is computed with
calculateRandomHash
In Scala/JS it's only a
counter++
The difference between K/JS and Scala/JS is only the
WeakMap
usage if it's available?
And the most significant difference is Scala/JS has two separate hash codes. The "id" one, and the one you can specify on your class/object.
Btw, I was looking at the identity hash code because I need an identity map in ANTLR
a
I proposed to add it into our stdlib based on JS Map. But the problem, that IdentityHashMap breaks some heuristics of all regular Map (especially the one about using of hashCode function) So, you can emulate it by yourself using just the regular JS Map
e
So, you can emulate it by yourself using just the regular JS Map
That was my initial idea, but what about the environments where a JS
Map
isn't available?
a
e
Thanks! I wanted to avoid polyfills, but it looks easier for now instead of emulating it on my own. At some point it would be nice to have that IdentityHashMap in the KMP stdlib tho.
e
Oh cool! So it looks like the use cases are there. Now I learn that Native has a
kotlin.native.identityHashCode
function in stdlib. A common function in stdlib for all targets seems doable 👀
1