Skip to content

Commit

Permalink
use separate set of ids
Browse files Browse the repository at this point in the history
  • Loading branch information
prashanDYDX committed Jun 4, 2024
1 parent 43134ea commit 57edf71
Showing 1 changed file with 9 additions and 33 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,46 +8,22 @@ fun mergeWithIds(
existing: List<Any>,
id: (Any) -> String?,
): List<Any> {
val merged = mutableSetOf<ItemWithId>()
val ids = mutableSetOf<String>()
val merged = mutableListOf<Any>()
new.forEach { item ->
id(item)?.let { itemId ->
merged.add(
ItemWithId(
id = itemId,
item = item,
),
)
ids.add(itemId)
merged.add(item)
}
}
existing.forEach { item ->
id(item)?.let { itemId ->
merged.add(
ItemWithId(
id = itemId,
item = item,
),
)
if (!ids.contains(itemId)) {
ids.add(itemId)
merged.add(item)
}
}
}

return merged.map { it.item }
}

// Wrapper for de-duping in set
private data class ItemWithId(
val id: String,
val item: Any,
) {
override fun hashCode(): Int {
return id.hashCode()
}

override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false

other as ItemWithId

return id == other.id
}
return merged
}

0 comments on commit 57edf71

Please sign in to comment.