How to translate a search query into a JavaScript filtering function

In a project I had to translate a search query into a filtering function to apply to a stream of JavaScript objects. The query language was very simple, boolean expressions of property constraints, for example “name:john AND age:52” where the search should return all the objects with property “name” equals to “john” and property “age” equals to 52.

The first step was to parse the search query with a parser. You can write a parser by hand or your can use a parser generator like PEG.js. I prefered the second one.

With the online editor I’ve wrote the language grammar:

The generated parser takes as input the text to parse and returns the parsed elements:

The grammar can be changed to make the parser method return a boolean expression:

The parser for a query like “name:john AND age:52” generates the following expression:

In the generated expression I’ve used an utility method that checks if the specified couple of name and value exists as property for the specified object:

The expression can be then passed as parameter in the function constructor:

Now you can use the new function as filter, for example with stream.js streams:

The grammar can be expanded with more operators and capabilities.