Skip to content

Commit

Permalink
perf: improve performance of computeChanges method
Browse files Browse the repository at this point in the history
  • Loading branch information
maxnowack committed Nov 25, 2024
1 parent cb0b9cf commit ac279ec
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions packages/signaldb/src/SyncManager/computeChanges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,23 @@ export default function computeChanges<T extends Record<string, any>>(
const modified: T[] = []
const removed: T[] = []

oldItems.forEach((oldItem) => {
const newItem = newItems.find(item => item.id === oldItem.id)
const oldItemsMap = new Map(oldItems.map(item => [item.id, item]))
const newItemsMap = new Map(newItems.map(item => [item.id, item]))

for (const [id, oldItem] of oldItemsMap) {
const newItem = newItemsMap.get(id)
if (!newItem) {
removed.push(oldItem)
return
} else if (!isEqual(newItem, oldItem)) {
modified.push(newItem)
}
}

for (const [id, newItem] of newItemsMap) {
if (!oldItemsMap.has(id)) {
added.push(newItem)
}
if (!isEqual(newItem, oldItem)) modified.push(newItem)
})
newItems.forEach((newItem) => {
const oldItem = oldItems.find(item => item.id === newItem.id)
if (oldItem) return
added.push(newItem)
})
}

return { added, modified, removed }
}

0 comments on commit ac279ec

Please sign in to comment.