This repository has been archived by the owner on Jun 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Players.swift
83 lines (72 loc) · 2.49 KB
/
Players.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import Combine
import GRDB
import GRDBCombine
import Dispatch
/// Players is responsible for high-level operations on the players database.
struct Players {
private let database: DatabaseWriter
init(database: DatabaseWriter) {
self.database = database
}
// MARK: - Modify Players
func deleteAll() throws {
try database.write { db in
_ = try Player.deleteAll(db)
}
}
func refresh() throws {
try database.write { db in
if try Player.fetchCount(db) == 0 {
// Insert new random players
for _ in 0..<8 {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
} else {
// Insert a player
if Bool.random() {
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
try player.insert(db)
}
// Delete a random player
if Bool.random() {
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
}
// Update some players
for var player in try Player.fetchAll(db) where Bool.random() {
player.score = Player.randomScore()
try player.update(db)
}
}
}
}
func stressTest() {
for _ in 0..<50 {
DispatchQueue.global().async {
try? self.refresh()
}
}
}
// MARK: - Access Players
/// A Hall of Fame
struct HallOfFame {
/// Total number of players
var playerCount: Int
/// The best ones
var bestPlayers: [Player]
static let empty = HallOfFame(playerCount: 0, bestPlayers: [])
}
/// A publisher that tracks changes in the Hall of Fame
func hallOfFamePublisher(maxPlayerCount: Int) -> DatabasePublishers.Value<HallOfFame> {
ValueObservation
.tracking(value: { db in
let playerCount = try Player.fetchCount(db)
let bestPlayers = try Player
.limit(maxPlayerCount)
.orderedByScore()
.fetchAll(db)
return HallOfFame(playerCount: playerCount, bestPlayers: bestPlayers)
})
.publisher(in: database)
}
}