Optimize private chat deduplication (#694)

This commit is contained in:
jack
2025-09-30 12:37:48 +02:00
committed by GitHub
parent f67f728d79
commit 85063e9359
+13 -8
View File
@@ -138,19 +138,24 @@ final class PrivateChatManager: ObservableObject {
/// Remove duplicate messages by ID and keep chronological order /// Remove duplicate messages by ID and keep chronological order
func sanitizeChat(for peerID: String) { func sanitizeChat(for peerID: String) {
guard let arr = privateChats[peerID] else { return } guard let arr = privateChats[peerID] else { return }
var seen = Set<String>() if arr.count <= 1 {
return
}
var indexByID: [String: Int] = [:]
indexByID.reserveCapacity(arr.count)
var deduped: [BitchatMessage] = [] var deduped: [BitchatMessage] = []
deduped.reserveCapacity(arr.count)
for msg in arr.sorted(by: { $0.timestamp < $1.timestamp }) { for msg in arr.sorted(by: { $0.timestamp < $1.timestamp }) {
if !seen.contains(msg.id) { if let existing = indexByID[msg.id] {
seen.insert(msg.id) deduped[existing] = msg
deduped.append(msg)
} else { } else {
// Replace previous with the latest occurrence (which is later in sort) indexByID[msg.id] = deduped.count
if let index = deduped.firstIndex(where: { $0.id == msg.id }) { deduped.append(msg)
deduped[index] = msg
}
} }
} }
privateChats[peerID] = deduped privateChats[peerID] = deduped
} }