diff --git a/.jules/bolt.md b/.jules/bolt.md new file mode 100644 index 0000000..3f3dcd7 --- /dev/null +++ b/.jules/bolt.md @@ -0,0 +1,3 @@ +## 2024-03-07 - [renderPDFs Filter Optimization] +**Learning:** In client-side filtering (like in Single Page Apps filtering large arrays without a framework), the order of conditions in array.filter matters heavily. String operations (.toLowerCase(), .includes()) are extremely expensive compared to basic equality checks (===) on primitive values. Concatenating strings over and over is also costly. +**Action:** Always place cheap strict equality checks first as early returns to prune the dataset before performing expensive string searching. Additionally, calculate and cache compound search strings on the objects lazily so they are only computed once per item, enabling rapid single-pass matching for subsequent searches. diff --git a/script.js b/script.js index bdc06f3..ac47b32 100644 --- a/script.js +++ b/script.js @@ -902,26 +902,24 @@ function renderPDFs() { // Locate renderPDFs() in script.js and update the filter section const filteredPdfs = pdfDatabase.filter(pdf => { - const matchesSemester = pdf.semester === currentSemester; + // ⚡ Bolt: Early returns for cheap equality checks to skip expensive string operations + if (pdf.semester !== currentSemester) return false; + if (pdf.class !== currentClass) return false; - // NEW: Check if the PDF class matches the UI's current class selection - // Note: If old documents don't have this field, they will be hidden. - const matchesClass = pdf.class === currentClass; - - let matchesCategory = false; if (currentCategory === 'favorites') { - matchesCategory = favorites.includes(pdf.id); - } else { - matchesCategory = currentCategory === 'all' || pdf.category === currentCategory; + if (!favorites.includes(pdf.id)) return false; + } else if (currentCategory !== 'all' && pdf.category !== currentCategory) { + return false; } - const matchesSearch = pdf.title.toLowerCase().includes(searchTerm) || - pdf.description.toLowerCase().includes(searchTerm) || - pdf.category.toLowerCase().includes(searchTerm) || - pdf.author.toLowerCase().includes(searchTerm); + if (!searchTerm) return true; + + // ⚡ Bolt: Lazily calculate and cache search string for efficient single-pass matching + if (!pdf._searchStr) { + pdf._searchStr = `${pdf.title || ''} ${pdf.description || ''} ${pdf.category || ''} ${pdf.author || ''}`.toLowerCase(); + } - // Update return statement to include matchesClass - return matchesSemester && matchesClass && matchesCategory && matchesSearch; + return pdf._searchStr.includes(searchTerm); }); updatePDFCount(filteredPdfs.length);