45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
const STORAGE_KEY = 'stb:visited-pots';
|
|
const MAX_ENTRIES = 20;
|
|
|
|
export interface VisitedPot {
|
|
slug: string;
|
|
name: string;
|
|
currency: string;
|
|
visitedAt: number;
|
|
}
|
|
|
|
type StorageLike = Pick<Storage, 'getItem' | 'setItem'>;
|
|
|
|
export function readVisitedPots(storage: StorageLike): VisitedPot[] {
|
|
const raw = storage.getItem(STORAGE_KEY);
|
|
if (!raw) return [];
|
|
|
|
try {
|
|
const parsed = JSON.parse(raw);
|
|
if (!Array.isArray(parsed)) return [];
|
|
return parsed.filter(
|
|
(item): item is VisitedPot =>
|
|
typeof item?.slug === 'string' &&
|
|
item.slug.trim() !== '' &&
|
|
typeof item?.name === 'string' &&
|
|
typeof item?.currency === 'string' &&
|
|
typeof item?.visitedAt === 'number',
|
|
);
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
export function recordVisitedPot(
|
|
storage: StorageLike,
|
|
pot: Omit<VisitedPot, 'visitedAt'>,
|
|
): VisitedPot[] {
|
|
const rest = readVisitedPots(storage).filter((p) => p.slug !== pot.slug);
|
|
const updated = [{ ...pot, visitedAt: Date.now() }, ...rest]
|
|
.sort((a, b) => b.visitedAt - a.visitedAt)
|
|
.slice(0, MAX_ENTRIES);
|
|
|
|
storage.setItem(STORAGE_KEY, JSON.stringify(updated));
|
|
return updated;
|
|
}
|