...
/Crafting a Generic Search Function
Crafting a Generic Search Function
Learn how to build a generic search function in TypeScript.
Now that our application successfully displays our widgets
and people
objects, we can start building our first functionality, a generic search function that we’ll call genericSearch
.
What is search, really?
In its most abstract form, searching is finding data that matches a query. In our situation, because we have already decided to map
over both the widgets
and people
variables, we could consider our search to just be the call to the JavaScript array filter
function before we call map
to render the items. With our current setup, that looks something like this:
<>{widgets.filter((widget) => genericSearch(widget, query).map(...)}{people.filter((person) => genericSearch(person, query).map(...)}</>
Our genericSearch
function will accept the object itself, as well as some sort of query to use to actually filter for the values.
Let’s start writing our genericSearch
function. First, we need to create a new folder called utils
and then a new file genericSearch.ts
. We can start ...