diff --git a/js/js.libraries/src/core/collections.kt b/js/js.libraries/src/core/collections.kt index f7d566870e0..52f54646867 100644 --- a/js/js.libraries/src/core/collections.kt +++ b/js/js.libraries/src/core/collections.kt @@ -17,6 +17,7 @@ package kotlin.collections import kotlin.comparisons.naturalOrder +import kotlin.js.Math /** Returns the array if it's not `null`, or an empty array otherwise. */ @kotlin.internal.InlineOnly @@ -85,12 +86,38 @@ public fun mapOf(pair: Pair): Map = hashMapOf(pair) * Each element in the list gets replaced with the [value]. */ @SinceKotlin("1.2") -public fun MutableList.fill(value: T) { +public fun MutableList.fill(value: T): Unit { for (index in 0..lastIndex) { this[index] = value } } +/** + * Randomly shuffles elements in this list. + * + * See: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm + */ +@SinceKotlin("1.2") +public fun MutableList.shuffle(): Unit { + for (i in lastIndex downTo 1) { + rand(i + 1).let { j -> + swap(this, i, j) + } +} +private fun rand(upperBound: Int) = Math.floor(Math.random() * upperBound) +private fun swap(list: MutableList, i: Int, j: Int): Unit { + val copy = list[i] + list[i] = list[j] + list[j] = copy +} + + +/** + * Returns a new list with the elements of this list randomly shuffled. + */ +@SinceKotlin("1.2") +public fun Iterable.shuffled(): List = toMutableList().apply { shuffle() } + /** * Sorts elements in the list in-place according to their natural sort order. */ @@ -112,7 +139,7 @@ private fun collectionsSort(list: MutableList, comparator: Comparator Array?.orEmpty(): Array expect inline fun Collection.toTypedArray(): Array -@SinceKotlin("1.2") -expect fun MutableList.fill(value: T): Unit -expect fun > MutableList.sort(): Unit -expect fun MutableList.sortWith(comparator: Comparator): Unit +@SinceKotlin("1.2") header fun MutableList.fill(value: T): Unit +@SinceKotlin("1.2") header fun MutableList.shuffle(): Unit +@SinceKotlin("1.2") header fun Iterable.shuffled(): List + +header fun > MutableList.sort(): Unit +header fun MutableList.sortWith(comparator: Comparator): Unit // from Grouping.kt diff --git a/libraries/stdlib/test/collections/MutableCollectionsTest.kt b/libraries/stdlib/test/collections/MutableCollectionsTest.kt index e60a8a5d7ac..40d2324f0b2 100644 --- a/libraries/stdlib/test/collections/MutableCollectionsTest.kt +++ b/libraries/stdlib/test/collections/MutableCollectionsTest.kt @@ -101,7 +101,6 @@ class MutableCollectionTest { assertEquals(listOf(42, 42, 42), list) } - @JvmVersion @Test fun shuffled() { val list = MutableList(100) { it } val shuffled = list.shuffled() @@ -127,6 +126,4 @@ class MutableCollectionTest { assertEquals(shuffled1, shuffled2) } - - }