Rename and refactor the types passed over the API to be based on an entity that's either living or a tombstone. A living entity has a deleted property that's either undefined or false, while a tombstone has a deleted property set to true. All entities have a numeric id and an updatedAt timestamp. To sync entities, an array of replacements are passed around. Living entities are replaced with tombstones when they're deleted. And tombstones are replaced with living entities when restored.
14 lines
415 B
TypeScript
14 lines
415 B
TypeScript
import type { Entity } from "~/shared/types/common";
|
|
|
|
export function applyUpdatesToArray<T extends Entity>(updates: T[], entities: T[]) {
|
|
const idMap = new Map(entities.map((e, i) => [e.id, i]));
|
|
for (const update of updates) {
|
|
const index = idMap.get(update.id);
|
|
if (index !== undefined) {
|
|
entities[index] = update;
|
|
} else {
|
|
idMap.set(update.id, entities.length);
|
|
entities.push(update);
|
|
}
|
|
}
|
|
}
|