Crossmate/Sync/GridStateMerger.swift (3743B)
1import Foundation
2
3
4
5
6
7
8
9
10
11enum GridStateMerger {
12
13
14
15
16
17
18 static func merge(_ moves: [MovesValue], notAfter cutoff: Date? = nil) -> GridState {
19 var grid: GridState = [:]
20 for (position, winner) in winners(moves, notAfter: cutoff) {
21 grid[position] = GridCell(
22 letter: winner.cell.letter,
23 mark: winner.cell.mark,
24 authorID: winner.cell.authorID
25 )
26 }
27 return grid
28 }
29
30
31
32
33
34
35 static func mergeWithProvenance(_ moves: [MovesValue]) -> [GridPosition: Provenance] {
36 var result: [GridPosition: Provenance] = [:]
37 for (position, winner) in winners(moves) {
38 result[position] = Provenance(
39 cell: winner.cell,
40 writerAuthorID: winner.writerAuthorID
41 )
42 }
43 return result
44 }
45
46 struct Provenance: Equatable {
47 var cell: TimestampedCell
48 var writerAuthorID: String
49 }
50
51 private static func winners(_ moves: [MovesValue], notAfter cutoff: Date? = nil) -> [GridPosition: Winner] {
52 var winners: [GridPosition: Winner] = [:]
53 for view in moves {
54 for (position, cell) in view.cells {
55 if let cutoff, cell.updatedAt > cutoff { continue }
56 let candidate = Winner(
57 cell: cell,
58 writerAuthorID: view.authorID,
59 deviceID: view.deviceID
60 )
61 if let current = winners[position] {
62 if shouldReplace(current: current, with: candidate) {
63 winners[position] = candidate
64 }
65 } else {
66 winners[position] = candidate
67 }
68 }
69 }
70 return winners
71 }
72
73 private struct Winner {
74 var cell: TimestampedCell
75 var writerAuthorID: String
76 var deviceID: String
77 }
78
79 private static func shouldReplace(current: Winner, with candidate: Winner) -> Bool {
80 let revisionOrder = candidate.cell.compareRevision(to: current.cell)
81 if revisionOrder != .orderedSame {
82 return revisionOrder == .orderedDescending
83 }
84 if candidate.writerAuthorID != current.writerAuthorID {
85 return candidate.writerAuthorID < current.writerAuthorID
86 }
87 return candidate.deviceID < current.deviceID
88 }
89}