I present to your attention a small js-library Jsqry .
The easiest way to illustrate its purpose is the following example.
Before:
var name; for (var i = 0; i < users.length; i++) { if (users[i].id == 123) { name = users[i].name; break; } }
After:
var name = one(users, '[_.id==?].name', 123);
The library allows you to extract information from objects / arrays in one line, using simple query language, instead of writing cycles (sometimes nested).
In fact, it implements only two functions:
The list of features includes:
The library appeared spontaneously in a single project built on the current one-page application approach. We load one big JSON, parts of which are then used to render different views of the site on the client. And for the tearing of these very parts, and wanted a more convenient way. Then, however, the library was in demand in other cases.
I will explain a little on the functional. The request can generally be
field1.field2[ condition or index or slice ].field3{ transformation }.field4
Here:
The condition and transformation should be discussed in more detail.
In fact, everything is very simple. It is enough to understand that each expression inside square / curly brackets when executed is replaced with a function according to this principle:
condition_or_transformation ⟶ function (_, i) {return condition_or_transformation }
(here _ is the value of the element being transmitted, i is its index).
Example:
query([1,2,3,4,5],'[_>2]{_+10}') // [13, 14, 15]
Also parameterization of the query is supported:
query([1,2,3,4,5],'[_>?]{_+?}', 2, 10) // [13, 14, 15]
By combining these capabilities, you can build highly complex and flexible queries. More examples of use can be found here .
From interesting in implementation - AST query tree is cached, which gives the library speed.
Of course, my library is not unique in its kind. It is necessary to give a "small" list of analogues:
Why another library? In fact, it does not support the entire possible range of request types, but only what was needed in our project in most cases. Due to this simplicity and speed. Also, an extremely simple API, inspired by the jQuery approach.
I will be glad to hear criticism and suggestions for improvement.
Source: https://habr.com/ru/post/303624/
All Articles