https://kotlinlang.org logo
#javascript
Title
# javascript
e

Edoardo Luppi

03/30/2024, 11:53 AM
A little detail I just discovered about the way
Array.sortedArray
works in JS. Under the hood Kotlin checks if the platform you're running JS on supports stable sort. I did not know this was the case, so there is a bit of processing going on in your first call of
sortedArray
Copy code
internal fun <T : Comparable<T>> sortArray(array: Array<out T>) {
    if (getStableSortingIsSupported()) {
        val comparison = { a: T, b: T -> a.compareTo(b) }
        array.asDynamic().sort(comparison)
    } else {
        mergeSort(array.unsafeCast<Array<T>>(), 0, array.lastIndex, naturalOrder())
    }
}

private var _stableSortingIsSupported: Boolean? = null
private fun getStableSortingIsSupported(): Boolean {
    _stableSortingIsSupported?.let { return it }
    _stableSortingIsSupported = false

    val array = js("[]").unsafeCast<Array<Int>>()
    // known implementations may use stable sort for arrays of up to 512 elements
    // so we create slightly more elements to test stability
    for (index in 0 until 600) array.asDynamic().push(index)
    val comparison = { a: Int, b: Int -> (a and 3) - (b and 3) }
    array.asDynamic().sort(comparison)
    for (index in 1 until array.size) {
        val a = array[index - 1]
        val b = array[index]
        if ((a and 3) == (b and 3) && a >= b) return false
    }
    _stableSortingIsSupported = true
    return true
}
I wonder if it wasn't just better to use the js
.sort
and write "beware it depends on the runtime"
c

CLOVIS

04/02/2024, 8:56 AM
I wonder if it wasn't just better to use the js
.sort
and write "beware it depends on the runtime"
Definitely not. The documentation says sorting is stable, there shouldn't be a small "but…" in the corner.
e

Edoardo Luppi

04/02/2024, 8:57 AM
Than, I think it should be made clear there is something going on in the background to establish stable/not stable
c

CLOVIS

04/02/2024, 8:58 AM
It's just on the very first use, right? this looks to me like typical platform-dependent optimizations
e

Edoardo Luppi

04/02/2024, 9:00 AM
Yes, but if I know my target platforms I may not want to incur the cost of lazily checking if stable sort is present or not. If the documentation states the check is present, consumers may opt to use their own function to delegate directly to JavaScript's sort.