BillTracker/client/lib/reorder.ts

28 lines
1.0 KiB
TypeScript
Raw Normal View History

interface Identified {
id: string | number;
}
export function moveInArray<T>(items: T[], fromIndex: number, toIndex: number): T[] {
if (!Array.isArray(items)) return [];
if (fromIndex === toIndex || fromIndex < 0 || toIndex < 0 || fromIndex >= items.length || toIndex >= items.length) {
return items;
}
const next = [...items];
const [moved] = next.splice(fromIndex, 1);
if (moved === undefined) return next; // in-range by the guard above; satisfies noUncheckedIndexedAccess
next.splice(toIndex, 0, moved);
return next;
}
export function reorderPayload(items: ReadonlyArray<Identified> | null | undefined): Record<string, number> {
return Object.fromEntries((items || []).map((item, index) => [item.id, index]));
}
export function movedItemId(
before: ReadonlyArray<Identified> | null | undefined,
after: ReadonlyArray<Identified> | null | undefined,
): string | number | null {
const moved = (after || []).find((item, index) => item.id !== before?.[index]?.id);
return moved?.id || after?.[0]?.id || null;
}