JSON pattern matching using JavaScript (Part 1-design)

Source: Internet
Author: User

As for the description of filter conditions, pattern matching is a common and useful method. In JavaScript, it is quite convenient to use JSON to describe the mode. So let's make a JSON mode matching tool.

Case Design
As a dispatcher, we only need two methods: Policy and capture. The simplest use case is as follows:
Copy codeThe Code is as follows:
Dispatcher. capture ({
"Status": 200,
"Command": "message"
}, Function (json) {/* display message */});

Dispatcher. Policy ({
Status: 200,
"Command": "message ",
"Content ":{
"From": "user1 ",
"To": "user2 ",
"Text": "hello"
}
});

Of course, only partial full-equality matching is not enough. We also need some other operators.
Copy codeThe Code is as follows:
Dispatcher. capture ({
"Value1 $ eq": "hello",/* equal */
"Value2 $ ne": true,/* not equal */
"Value3 $ lt": 0,/* less */
"Value4 $ lte: 1,/* less than or equal */
"Value5 $ gt": 2,/* greater */
"Value6 $ gte": 3,/* greater than or equal */
"Value7 $ in": [1, 3, 5, 7, 9],/* in */
"Value8 $ nin": [2, 4, 6, 8, 10],/* not in */
"Value9 $ all": [1, 2, 3, 4, 5],/* all */
"Value10 $ ex": true,/* exists */
"Value11 $ re":/^ A. */,/* regular expression */
"Value12 $ ld": function (json) {return true;}/* lambda */
}, Function (json ){});

Dispatcher. Policy ({
"Value1": "hello ",
"Value2": false,
"Value3":-1,
"Value4": 1,
"Value5": 3,
"Value6": 3,
"Value7": 5,
"Value8": 5,
"Value9": [1, 3, 5, 2, 4],
"Value10": "hello ",
"Value11": "A13579 ",
"Value12": "anything"
})

Write down a bunch of operators at will, which seems complicated to implement? In fact, there will not be much complexity. In the next article, we will discuss how to design an Operator Interface and implement these operators one by one.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.