Skip to content

Commit 5324a5b

Browse files
jeffersonsetiawanstephencelis
authored andcommitted
Add implementation of shuffle on IdentifiedArray (#254)
* add shuffle * Update Tests/ComposableArchitectureTests/IdentifiedArrayTests.swift * Update IdentifiedArrayTests.swift Co-authored-by: Stephen Celis <[email protected]>
1 parent 0369187 commit 5324a5b

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

Sources/ComposableArchitecture/SwiftUI/IdentifiedArray.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,15 @@ where ID: Hashable {
191191
try areInIncreasingOrder(self.dictionary[$0]!, self.dictionary[$1]!)
192192
}
193193
}
194+
195+
public mutating func shuffle<T>(using generator: inout T) where T : RandomNumberGenerator {
196+
ids.shuffle(using: &generator)
197+
}
198+
199+
public mutating func shuffle() {
200+
var rng = SystemRandomNumberGenerator()
201+
self.shuffle(using: &rng)
202+
}
194203
}
195204

196205
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)

Tests/ComposableArchitectureTests/IdentifiedArrayTests.swift

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,4 +196,36 @@ final class IdentifiedArrayTests: XCTestCase {
196196
], array)
197197

198198
}
199+
200+
// Account for randomness API changes in Swift 5.3 (https://twitter.com/mbrandonw/status/1262388756847505410)
201+
// TODO: Try swapping out the LCRNG for a Xoshiro generator
202+
#if swift(>=5.3)
203+
func testShuffle() {
204+
struct User: Equatable, Identifiable {
205+
let id: Int
206+
var name: String
207+
}
208+
209+
var array: IdentifiedArray = [
210+
User(id: 1, name: "Blob"),
211+
User(id: 2, name: "Blob Jr."),
212+
User(id: 3, name: "Blob Sr."),
213+
User(id: 4, name: "Foo Jr."),
214+
User(id: 5, name: "Bar Jr."),
215+
]
216+
var lcrng = LCRNG(seed: 0)
217+
array.shuffle(using: &lcrng)
218+
XCTAssertEqual(
219+
[
220+
User(id: 1, name: "Blob"),
221+
User(id: 3, name: "Blob Sr."),
222+
User(id: 5, name: "Bar Jr."),
223+
User(id: 4, name: "Foo Jr."),
224+
User(id: 2, name: "Blob Jr.")
225+
],
226+
array.elements
227+
)
228+
XCTAssertEqual([1, 3, 5, 4, 2], array.ids)
229+
}
230+
#endif
199231
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/// A linear congruential random number generator.
2+
public struct LCRNG: RandomNumberGenerator {
3+
public var seed: UInt64
4+
5+
@inlinable
6+
public init(seed: UInt64) {
7+
self.seed = seed
8+
}
9+
10+
@inlinable
11+
public mutating func next() -> UInt64 {
12+
seed = 2862933555777941757 &* seed &+ 3037000493
13+
return seed
14+
}
15+
}

0 commit comments

Comments
 (0)