This commit is contained in:
+29
-25
@@ -1,40 +1,44 @@
|
||||
const STORAGE_KEY = 'stb:visited-pots'
|
||||
const MAX_ENTRIES = 20
|
||||
const STORAGE_KEY = 'stb:visited-pots';
|
||||
const MAX_ENTRIES = 20;
|
||||
|
||||
export interface VisitedPot {
|
||||
slug: string
|
||||
name: string
|
||||
currency: string
|
||||
visitedAt: number
|
||||
slug: string;
|
||||
name: string;
|
||||
currency: string;
|
||||
visitedAt: number;
|
||||
}
|
||||
|
||||
type StorageLike = Pick<Storage, 'getItem' | 'setItem'>
|
||||
type StorageLike = Pick<Storage, 'getItem' | 'setItem'>;
|
||||
|
||||
export function readVisitedPots(storage: StorageLike): VisitedPot[] {
|
||||
const raw = storage.getItem(STORAGE_KEY)
|
||||
if (!raw) return []
|
||||
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 []
|
||||
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)
|
||||
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)
|
||||
.slice(0, MAX_ENTRIES);
|
||||
|
||||
storage.setItem(STORAGE_KEY, JSON.stringify(updated))
|
||||
return updated
|
||||
storage.setItem(STORAGE_KEY, JSON.stringify(updated));
|
||||
return updated;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user