Pattern matching of JSON with JavaScript (Part 2-implementation) _javascript tips

Source: Internet
Author: User
Tags switch case
Notify & Capture
To achieve notify and capture is too easy, we just have to save capture incoming handler, and then find a matching notify inside handler on it.
Copy Code code as follows:

var filterhandlerbundles = [];
Dispatch.capture = function (pattern, handler) {
var filter = Createfilter (pattern);
Filterhandlerbundles.push ({
"Filter": Filter,
"Handler": Handler
});
};
Dispatcher.notify = function (JSON) {
for (var i = 0; i < filterhandlerbundles.length; i++) {
if (filterhandlerbundles[i].filter.apply (this, arguments)) {
Filterhandlerbundles[i].handler (JSON);
}
}
};

The logic of this code is very clear, the key lies in the Createfilter part. This function is responsible for converting a JSON that describes a pattern into a function that determines whether JSON matches.
Operators
We have designed a lot of algorithms, how to achieve them? Remember, we don't switch case. Therefore, we use an associative array to hold the mapping relationship between the operator and the implementation.
Copy Code code as follows:

var operators = {};
operators["LT"] = function (TestValue, value) {
return arguments.length = = 2 && value < TestValue;
};
Operators["LTE" = function (TestValue, value) {
return arguments.length = = 2 && value <= testvalue;
};
operators["GT" = function (TestValue, value) {
return arguments.length = = 2 && value > testvalue;
};
Operators["GTE"] = function (TestValue, value) {
return arguments.length = = 2 && value >= testvalue;
};

So we can immediately find the corresponding judgment function by extracting the operator after "$". The above 4 are comparison operators, because the implementation is relatively easy, so put it here for example.
A more difficult function is the EQ, because it needs to select a specific method of judgment based on the type of data. For String, number, Boolean, eq means = = =; For Array, eq means that every element in it is EQ and in the same order; for Object, eq means that every child condition fits, so we need to put each The operator string for the child condition is extracted, and then the corresponding operator is invoked. You can refer to the complete code.
The other operators will be simpler, and I'll just give you a hint that you can set a subset or superset of these operators according to your actual needs:

In-traverses the array to see if you can find at least one EQ.
All-iterate over the array to see if every one has an EQ.
Ex-if there is an incoming value, the child element exists.
Re-use regular expressions to determine whether strings match.
LD-Direct call function for judgment.
Did you write it? Not sure if you wrote it correctly? This is what we're going to discuss in our next article, let's add a default operator first.
Copy Code code as follows:

Operators[""] = function (TestValue, value) {
if (TestValue instanceof Array) {
Return operators[' in '].apply (this, arguments);
else if (TestValue instanceof RegExp) {
Return operators["Re"].apply (this, arguments);
else if (TestValue instanceof Function) {
Return operators[the "LD"].apply (this, arguments);
} else {
return operators[' eq '].apply (this, arguments);
}
};

Why do I need a default operator? This is actually just a shortcut. Most of the time, all we need is an EQ operation, and if you write the operators in each place, the code will become complex and unattractive. Compared to two JSON, which one do you think is more natural?
Copy Code code as follows:

Dispatcher.capture ({
"Status": 200,
"Command": "Message"
}, function (JSON) {/* Display message */});
Dispatcher.capture ({
"Status$eq": 200,
"Command$eq": "Message"
}, function (JSON) {/* Display message */});

Obviously, the first one is more intuitive. Therefore, we need a default operator that, when the operator string is "", selects an operator by default operator.
Pattern to Filter
Finally, we need to connect operators and Createfilter. This part of the work is not difficult, as long as the default operator can be invoked.
Copy Code code as follows:

var createfilter = function (condition) {
return function (JSON) {
if (Arguments.length > 0) {
Return operators[""] (condition, JSON);
} else {
Return operators[""] (condition);
}
};
};

Why do I need to consider the case where the JSON parameter is not passed in? I'll tell you the next article. It's OK not to do it, just some very small problems.
Write operators, the most needed is rigor. Because Dispatcher is a packaged component, the operator is a little bit less rigorous, it will bury the defect very deep, it is difficult to find out. Therefore, the next article we want to discuss is unit test, through unit test we can greatly improve the robustness of Dispatcher.

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.