A little detail I just discovered about the way `A...
# javascript
e
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
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
Than, I think it should be made clear there is something going on in the background to establish stable/not stable
c
It's just on the very first use, right? this looks to me like typical platform-dependent optimizations
e
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.