chore(applyChanges): cleanup

This commit is contained in:
moklick
2024-08-28 16:21:38 +02:00
parent 12dbe12575
commit e3890f7e38
+11 -5
View File
@@ -19,11 +19,11 @@ function applyChanges(changes: any[], elements: any[]): any[] {
// By storing a map of changes for each element, we can a quick lookup as we // By storing a map of changes for each element, we can a quick lookup as we
// iterate over the elements array! // iterate over the elements array!
const changesMap = new Map<any, any[]>(); const changesMap = new Map<any, any[]>();
const newItems: any[] = []; const addItemChanges: any[] = [];
for (const change of changes) { for (const change of changes) {
if (change.type === 'add') { if (change.type === 'add') {
newItems.push(change); addItemChanges.push(change);
continue; continue;
} else if (change.type === 'remove' || change.type === 'replace') { } else if (change.type === 'remove' || change.type === 'replace') {
// For a 'remove' change we can safely ignore any other changes queued for // For a 'remove' change we can safely ignore any other changes queued for
@@ -74,9 +74,15 @@ function applyChanges(changes: any[], elements: any[]): any[] {
updatedElements.push(updatedElement); updatedElements.push(updatedElement);
} }
if (newItems.length) { // we need to wait for all changes to be applied before adding new items
newItems.forEach((item) => { // to be able to add them at the correct index
updatedElements.splice(item.index, 0, { ...item.item }); if (addItemChanges.length) {
addItemChanges.forEach((change) => {
if (change.index !== undefined) {
updatedElements.splice(change.index, 0, { ...change.item });
} else {
updatedElements.push({ ...change.item });
}
}); });
} }