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.