Files
CapaKraken/apps/web/src/hooks/timelineOptimisticAllocations.ts
T

52 lines
1.5 KiB
TypeScript

export type OptimisticTimelineEntryLike = {
id: string;
startDate: Date | string;
endDate: Date | string;
};
export type OptimisticTimelineOverrideLike = {
startDate: Date;
endDate: Date;
};
export function reconcileOptimisticEntries(
optimisticAllocations: ReadonlyMap<string, OptimisticTimelineOverrideLike>,
entries: readonly OptimisticTimelineEntryLike[],
pendingOptimisticAllocationId: string | null,
): {
optimisticAllocations: Map<string, OptimisticTimelineOverrideLike>;
pendingOptimisticAllocationId: string | null;
changed: boolean;
} {
if (optimisticAllocations.size === 0) {
return {
optimisticAllocations: new Map(optimisticAllocations),
pendingOptimisticAllocationId,
changed: false,
};
}
const next = new Map(optimisticAllocations);
let nextPendingId = pendingOptimisticAllocationId;
for (const entry of entries) {
const override = next.get(entry.id);
if (!override) continue;
const startTime = new Date(entry.startDate).getTime();
const endTime = new Date(entry.endDate).getTime();
if (startTime === override.startDate.getTime() && endTime === override.endDate.getTime()) {
next.delete(entry.id);
if (nextPendingId === entry.id) {
nextPendingId = null;
}
}
}
return {
optimisticAllocations: next,
pendingOptimisticAllocationId: nextPendingId,
changed: next.size !== optimisticAllocations.size || nextPendingId !== pendingOptimisticAllocationId,
};
}