diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 0000000..41d301d --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,3 @@ +## 2024-03-20 - Cache favorites array to avoid redundant JSON parsing +**Learning:** During render loops, the code was repeatedly calling `getFavorites()`, which read from `localStorage` synchronously and `JSON.parse`d the data each time. This caused performance degradation in tight loops rendering the PDF list. +**Action:** Created `favoritesCache` global variable. `getFavorites()` will return `favoritesCache` if it is not null, otherwise read and parse from `localStorage` once. `toggleFavorite()` will update `favoritesCache` whenever a favorite is toggled. Next time I notice repetitive synchronous operations like `localStorage.getItem` combined with expensive conversions like `JSON.parse` inside render loops, I will consider using an in-memory cache to retrieve values instantly. diff --git a/script.js b/script.js index 22f399d..79e9d45 100644 --- a/script.js +++ b/script.js @@ -13,6 +13,9 @@ let adDatabase = {}; let isModalHistoryPushed = false; let db; // Defined globally, initialized later +// ⚡ Bolt: Cache favorites to prevent synchronous JSON.parse in the render loop +let favoritesCache = null; + // GAS const GAS_URL = "https://script.google.com/macros/s/AKfycby2lW5QdidC7o_JX0jlXa59uAjmmpFzOx-rye0N1x0r6hoYu-1CB65YrM1wPr7h-tZu/exec" // DOM Elements @@ -1319,8 +1322,13 @@ async function handleCommentSubmit(e) { 10. EXTRAS (THEME, FAVORITES, EASTER EGGS) ========================================= */ function getFavorites() { + // ⚡ Bolt: Use cached favorites if available to avoid redundant JSON parsing + if (favoritesCache !== null) { + return favoritesCache; + } const stored = localStorage.getItem('classNotesFavorites'); - return stored ? JSON.parse(stored) : []; + favoritesCache = stored ? JSON.parse(stored) : []; + return favoritesCache; } function toggleFavorite(event, pdfId) { @@ -1339,6 +1347,8 @@ function toggleFavorite(event, pdfId) { favorites.push(pdfId); showToast('Added to saved notes'); } + // ⚡ Bolt: Update cache whenever favorites list changes + favoritesCache = favorites; localStorage.setItem('classNotesFavorites', JSON.stringify(favorites)); renderPDFs(); }