Skip to content

Commit f84e0db

Browse files
author
Pap Lőrinc
committed
Provide java.util.Collections#shuffle as extensions for collections in JS
Fixes: #KT-2460
1 parent 1622e91 commit f84e0db

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

js/js.libraries/src/core/collections.kt

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,27 @@ public fun <T> MutableList<T>.fill(value: T): Unit {
9191
}
9292
}
9393

94+
/**
95+
* Randomly shuffles elements in this list.
96+
*
97+
* See: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
98+
*/
99+
@SinceKotlin("1.2")
100+
public fun <T> MutableList<T>.shuffle(): Unit {
101+
(lastIndex downTo 1).forEach { i ->
102+
rand(i + 1).let { j ->
103+
swap(i, j)
104+
}
105+
}
106+
}
107+
private fun rand(upperBound: Int) = Math.floor(Math.random() * upperBound)
108+
109+
/**
110+
* Returns a new list with the elements of this list randomly shuffled.
111+
*/
112+
@SinceKotlin("1.2")
113+
public fun <T> Iterable<T>.shuffled(): List<T> = toMutableList().apply { shuffle() }
114+
94115
/**
95116
* Sorts elements in the list in-place according to their natural sort order.
96117
*/

libraries/stdlib/common/src/kotlin/CollectionsH.kt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,9 @@ header inline fun <reified T> Array<out T>?.orEmpty(): Array<out T>
150150
header inline fun <reified T> Collection<T>.toTypedArray(): Array<T>
151151

152152
@SinceKotlin("1.2") header fun <T> MutableList<T>.fill(value: T): Unit
153+
@SinceKotlin("1.2") header fun <T> MutableList<T>.shuffle(): Unit
154+
@SinceKotlin("1.2") header fun <T> Iterable<T>.shuffled(): List<T>
155+
153156
header fun <T : Comparable<T>> MutableList<T>.sort(): Unit
154157
header fun <T> MutableList<T>.sortWith(comparator: Comparator<in T>): Unit
155158

libraries/stdlib/test/collections/MutableCollectionsTest.kt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,6 @@ class MutableCollectionTest {
101101
assertEquals(listOf(42, 42, 42), list)
102102
}
103103

104-
@JvmVersion
105104
@Test fun shuffled() {
106105
val list = MutableList(100) { it }
107106
val shuffled = list.shuffled()

0 commit comments

Comments
 (0)