Let us say we have the following JavaScript array:
const books = [
{
title: "The Great Gatsby",
description: "A novel about the decadence of the Roaring Twenties and the American Dream"
},
{
title: "To Kill a Mockingbird",
description: "A classic novel about racial injustice and growing up in the South"
},
{
title: "1984",
description: "A dystopian novel about a totalitarian government that controls every aspect of its citizens' lives"
}
];
Now I want to filter the books according to the user query. The code then looks like this:
function validateQuery(string, query) {
}
books.filter(book => validateQuery(book.title, "Gatsby great"));
Let us say we are looking for the book The Great Gatsby
All of these queries should return true
when being passed to the validateQuery
function:
- Gatsby great
- The great
- Gre th
-
- The grea gatsby *
Which means that:
- the query is case insensitive
- multiple whitespaces at the start and end of the query and inbetween the words are not a problem
- the order of the words does not matter
- the words do not have to be right next to each other, so it is like multiple words
What could the body of the validateQuery
function look like?
I thought of using RegExp to solve the problem, but maybe there is an even simpler solution which does not need RegEx. Maybe there is also a common algorithm out there to solve this problem, even though I did not find anything on Google.