I am trying to access a JavaScript object that rep...
# javascript
h
I am trying to access a JavaScript object that represents a
Map<String, Set<String>>
. This works fine if I serialize using
JSON.stringify()
and then use KotlinX Serialization to Deserialize. This has a performance hit to do this serialization. I know
Map
is not a natively supported interop type with JS, but was trying to see if it was faster to use some of the
kotlin-wrappers
(https://github.com/JetBrains/kotlin-wrappers) to create transformer functions to go from one to the other. I ended up with some really gross code that "works", but the performance seems to be the equivalent to Json Serialization and seems much more fragile. Any tips? I'll share my horribly hacky code in the thread. ➡️
Goal is to transform into an object like
Map<String, Map<String, Set<String>>>
My
external interface
for JS is:
Copy code
external interface ExternalJsModel {
  val map: JsMap<String, JsMap<String, Array<String>>>
}
Converter Function (it does work...) 🤮
Copy code
fun convert(obj: JsMap<String, JsMap<String, Array<String>>>): Map<String, Map<String, Set<String>>> {
    return Object.entries(obj).map { firstLayer ->
      firstLayer.component1() to run {
        val firstLayerEntries = Object.entries(firstLayer.component2()!!)
        firstLayerEntries.associate { firstLayerEntry ->
          firstLayerEntry.component1() to run {
            val secondLayerEntry = firstLayerEntry.component2()!!
            Object.values(secondLayerEntry).toSet()
          }
        } as Map<String, Set<String>>
      }.toMap()
    }.toMap()
  }
a
Just want to mention, that for the compiler itself, we already have PoC for supporting this conversion natively. (kotlin.collections.Map - Map, kotlin.collections.List - Array, kotlin.collections.Set - Set). It should be available in 2.0.0
t
Looks like single
Map.toJsMap(valueTransformer)
will be fine
Also
JsSet
can be used
h
Nice, I'm using 2.0.0-Beta2 of Kotlin and didn't see anything yet. I'm happy to wait until support is natively there. I didn't see
Map.toJsMap(valueTransformer)
, so can look into that if the native support for
external interface
is not added in 2.0.0 stable
t
>
Map.toJsMap(valueTransformer)
At start it will be your local function 😉