Edoardo Luppi
03/30/2024, 11:53 AMArray.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
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
}
Edoardo Luppi
03/30/2024, 12:34 PM.sort
and write "beware it depends on the runtime"CLOVIS
04/02/2024, 8:56 AMI wonder if it wasn't just better to use the jsDefinitely not. The documentation says sorting is stable, there shouldn't be a small "but…" in the corner.and write "beware it depends on the runtime".sort
Edoardo Luppi
04/02/2024, 8:57 AMCLOVIS
04/02/2024, 8:58 AMEdoardo Luppi
04/02/2024, 9:00 AM