Add implementation of shuffle on IdentifiedArray (#254)

* add shuffle

* Update Tests/ComposableArchitectureTests/IdentifiedArrayTests.swift

* Update IdentifiedArrayTests.swift

Co-authored-by: Stephen Celis <stephen.celis@gmail.com>
This commit is contained in:
Jefferson Setiawan
2020-08-14 06:52:14 +07:00
committed by GitHub
parent 86843a4dcc
commit fffefb9c22
3 changed files with 56 additions and 0 deletions

View File

@@ -190,6 +190,15 @@ where ID: Hashable {
try areInIncreasingOrder(self.dictionary[$0]!, self.dictionary[$1]!) try areInIncreasingOrder(self.dictionary[$0]!, self.dictionary[$1]!)
} }
} }
public mutating func shuffle<T>(using generator: inout T) where T : RandomNumberGenerator {
ids.shuffle(using: &generator)
}
public mutating func shuffle() {
var rng = SystemRandomNumberGenerator()
self.shuffle(using: &rng)
}
} }
extension IdentifiedArray: CustomDebugStringConvertible { extension IdentifiedArray: CustomDebugStringConvertible {

View File

@@ -195,4 +195,36 @@ final class IdentifiedArrayTests: XCTestCase {
], array) ], array)
} }
// Account for randomness API changes in Swift 5.3 (https://twitter.com/mbrandonw/status/1262388756847505410)
// TODO: Try swapping out the LCRNG for a Xoshiro generator
#if swift(>=5.3)
func testShuffle() {
struct User: Equatable, Identifiable {
let id: Int
var name: String
}
var array: IdentifiedArray = [
User(id: 1, name: "Blob"),
User(id: 2, name: "Blob Jr."),
User(id: 3, name: "Blob Sr."),
User(id: 4, name: "Foo Jr."),
User(id: 5, name: "Bar Jr."),
]
var lcrng = LCRNG(seed: 0)
array.shuffle(using: &lcrng)
XCTAssertEqual(
[
User(id: 1, name: "Blob"),
User(id: 3, name: "Blob Sr."),
User(id: 5, name: "Bar Jr."),
User(id: 4, name: "Foo Jr."),
User(id: 2, name: "Blob Jr.")
],
array.elements
)
XCTAssertEqual([1, 3, 5, 4, 2], array.ids)
}
#endif
} }

View File

@@ -0,0 +1,15 @@
/// A linear congruential random number generator.
public struct LCRNG: RandomNumberGenerator {
public var seed: UInt64
@inlinable
public init(seed: UInt64) {
self.seed = seed
}
@inlinable
public mutating func next() -> UInt64 {
seed = 2862933555777941757 &* seed &+ 3037000493
return seed
}
}