Skip to content

Commit 65b5b6f

Browse files
committed
Eliminate duplicates when replacing the model
1 parent b4f63ed commit 65b5b6f

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

Sources/GravatarUI/SwiftUI/AvatarPicker/AvatarGridModel.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,16 @@ class AvatarGridModel: ObservableObject {
2525
func replaceModel(withID id: String, with model: AvatarImageModel) {
2626
guard let index = index(of: id) else { return }
2727
avatars[index] = model
28+
removeDuplicates(of: model, atIndex: index)
29+
}
30+
31+
/// Keep the model at `index`, remove the rest that has the same `id`.
32+
private func removeDuplicates(of model: AvatarImageModel, atIndex index: Int) {
33+
for (indexIter, modelIter) in avatars.enumerated() {
34+
if modelIter.id == model.id && indexIter != index {
35+
avatars.remove(at: indexIter)
36+
}
37+
}
2838
}
2939

3040
func removeModel(_ id: String) {

Tests/GravatarUITests/AvatarGridModelTests.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,4 +107,24 @@ struct AvatarGridModelTests {
107107

108108
#expect(model.index(of: "new") == 2)
109109
}
110+
111+
@Test("Test replace function")
112+
func testAvatarGridModelReplace() async throws {
113+
let toReplace = AvatarImageModel(id: "new", source: .remote(url: "https://example.com"))
114+
model.replaceModel(withID: "0", with: toReplace)
115+
116+
#expect(model.index(of: "new") == 0)
117+
}
118+
119+
@Test("Test replace with an existing ID")
120+
func testAvatarGridModelReplaceWithExistingID() async throws {
121+
// An element with ID "4" already exists in the model
122+
let toReplace = AvatarImageModel(id: "4", source: .remote(url: "https://example.com"))
123+
// Replace an existing element with a new element whose ID is "4".
124+
model.replaceModel(withID: "0", with: toReplace)
125+
// Check how many items are present with ID == "4"
126+
let avatarCount = model.avatars.filter { $0.id == "4" }.count
127+
#expect(avatarCount == 1)
128+
#expect(model.index(of: "4") == 0)
129+
}
110130
}

0 commit comments

Comments
 (0)