From aa289de836f9ebe0707258a806cf784bc8549c9c Mon Sep 17 00:00:00 2001 From: Emil Miler Date: Fri, 9 Dec 2022 13:17:29 +0100 Subject: [PATCH] Search optimisation These changes make the code more efficient, since going trough an array with `forEach` is faster than iterating with a foor loop on every input change. Using `indexOf()` instead of `includes()` is faster as well. --- static/js/search.js | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/static/js/search.js b/static/js/search.js index 57b57ad..4256301 100644 --- a/static/js/search.js +++ b/static/js/search.js @@ -1,16 +1,11 @@ function filter_name(str) { if (str.length == 0) { - for (let i = 0; i < articles.length; i++) { - articles[i].style.display = "block"; - } + articles.forEach(article => article.style.display = "block"); } else { - str = str.toLowerCase(); - for (let i = 0; i < articles.length; i++) { - articles[i].style.display = !articles[i].dataset.title.includes(str) ? "none" : "block"; - } + articles.forEach(article => article.style.display = article.dataset.title.indexOf(str.toLowerCase()) === -1 ? "none" : "block"); } } -let articles = document.getElementsByTagName("article"); -let search = document.getElementById("search"); -search.style.display = "inline-block"; + +let articles = Array.from(document.getElementsByTagName("article")); +document.getElementById("search").style.display = "inline-block";