Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

As an exercise for myself to practice my JavaScript \"skills\" I\'m trying to wr

ID: 647372 • Letter: A

Question

As an exercise for myself to practice my JavaScript "skills" I'm trying to write a client-side filter. It should be able to filter "content blocks" as the user types.

By "content block", I mean a list of DomElements that each contain at least one text node - it is possible that they contain more, and even a different amount of text nodes, nested inside other nodes, etc.

I've thought of 2 approaches:

On page initialization, scan all nodes and store all the text in some kind of Map or a tree.

Simply iterate over every item and check whether it has the string to search/filter for. One could add performance here by caching, only filtering the current remaining items if text is added, etc.

Obviously, if the number of nodes is really big, option 1 will take a while to build the 'index' but it will perform faster once it is built. Option 2 however will be available right on page load since no initialization is performed. But of course it will take longer to search.

So my question is: what is the best approach here? And how would one implement 'caching' and/or 'index'?

Explanation / Answer

I believe that, a mix between both would be great.

First time it will build the index while doing the search. It will take a little more time to search, but after it will search much faster by the built indexed cache.

Thinking in the nested data situation, and considering that the search will be done a lot of times, i would make a cache not indexed, in the same tree disposition of the data, and a cache of search results.

e.g.
The result cache should be indexed by search results (less first)

User search first time for javascript, in the end of the search there will be

a list of all texts to search linearly
a result list for javascript
User search for nodejs, in the end of the search there will be

a list of all texts to search linearly
2 result list (1 for javascript and 1 for nodejs)
User search for javascript nodejs, it will search in the smallest list and, in the end of the search there will be

a list of all texts to search linearly
3 result list (1 for javascript, 1 for nodejs and 1 for javascript nodejs)