Provide java.util.Collections#shuffle as extensions for collections in JS

#KT-2460
This commit is contained in:
Pap Lorinc
2017-09-17 20:43:26 +03:00
committed by Ilya Gorbunov
parent 6fc87c532e
commit e640867238
3 changed files with 35 additions and 9 deletions
+29 -2
View File
@@ -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 <K, V> mapOf(pair: Pair<K, V>): Map<K, V> = hashMapOf(pair)
* Each element in the list gets replaced with the [value].
*/
@SinceKotlin("1.2")
public fun <T> MutableList<T>.fill(value: T) {
public fun <T> MutableList<T>.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 <T> MutableList<T>.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<T>, 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 <T> Iterable<T>.shuffled(): List<T> = toMutableList().apply { shuffle() }
/**
* Sorts elements in the list in-place according to their natural sort order.
*/
@@ -112,7 +139,7 @@ private fun <T> collectionsSort(list: MutableList<T>, comparator: Comparator<in
array.asDynamic().sort(comparator.asDynamic().compare.bind(comparator))
for (i in 0..array.size - 1) {
for (i in 0..array.lastIndex) {
list[i] = array[i]
}
}
@@ -149,10 +149,12 @@ expect inline fun <reified T> Array<out T>?.orEmpty(): Array<out T>
expect inline fun <reified T> Collection<T>.toTypedArray(): Array<T>
@SinceKotlin("1.2")
expect fun <T> MutableList<T>.fill(value: T): Unit
expect fun <T : Comparable<T>> MutableList<T>.sort(): Unit
expect fun <T> MutableList<T>.sortWith(comparator: Comparator<in T>): Unit
@SinceKotlin("1.2") header fun <T> MutableList<T>.fill(value: T): Unit
@SinceKotlin("1.2") header fun <T> MutableList<T>.shuffle(): Unit
@SinceKotlin("1.2") header fun <T> Iterable<T>.shuffled(): List<T>
header fun <T : Comparable<T>> MutableList<T>.sort(): Unit
header fun <T> MutableList<T>.sortWith(comparator: Comparator<in T>): Unit
// from Grouping.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)
}
}