// 최근 본 종목 — localStorage 기반. 종목 페이지 진입 시 자동으로 push. // 단순 string[] 직렬화. 최신이 앞쪽, 최대 MAX 개로 캡. const KEY = "stockchart.recent"; const MAX = 10; function read(): string[] { if (typeof window === "undefined") return []; try { const raw = window.localStorage.getItem(KEY); if (!raw) return []; const v = JSON.parse(raw); return Array.isArray(v) ? v.filter((s) => typeof s === "string") : []; } catch { return []; } } function write(codes: string[]) { if (typeof window === "undefined") return; window.localStorage.setItem(KEY, JSON.stringify(codes)); // 같은 탭은 storage 이벤트가 안 떠서 수동 dispatch. window.dispatchEvent(new CustomEvent("recent:change")); } export const recent = { get(): string[] { return read(); }, push(code: string): void { if (!code) return; const cur = read().filter((c) => c !== code); cur.unshift(code); write(cur.slice(0, MAX)); }, clear(): void { write([]); }, subscribe(cb: () => void): () => void { if (typeof window === "undefined") return () => {}; const onStorage = (e: StorageEvent) => { if (e.key === KEY) cb(); }; const onCustom = () => cb(); window.addEventListener("storage", onStorage); window.addEventListener("recent:change", onCustom as EventListener); return () => { window.removeEventListener("storage", onStorage); window.removeEventListener("recent:change", onCustom as EventListener); }; }, };