Heim  >  Artikel  >  Web-Frontend  >  用JavaScript对JSON进行模式匹配(Part 1-设计)_javascript技巧

用JavaScript对JSON进行模式匹配(Part 1-设计)_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:23:091004Durchsuche

至于筛选条件的描述,模式匹配是一种很常见也很好用的方式。在 JavaScript 里面,用 JSON 来描述模式又是相当方便的事情,所以我们来做一个 JSON 模式匹配工具吧。

用例设计
作为一个 dispatcher ,我们只需要两个方法: notify 和 capture 。一个最简单的用例是这样的:

复制代码 代码如下:

Dispatcher.capture({
"status": 200,
"command": "message"
}, function(json) { /* display message */ });

Dispatcher.notify({
“status": 200,
"command": "message",
"content": {
"from": "user1",
"to": "user2",
"text": "hello"
}
});

当然,只有局部的全等匹配是不够的,我们还需要一些其他运算符。
复制代码 代码如下:

Dispatcher.capture({
"value1$eq": "hello", /* equal */
"value2$ne": true, /* not equal */
"value3$lt": 0, /* less than */
"value4$lte: 1, /* less than or equal */
"value5$gt": 2, /* greater than */
"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.notify({
"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"
})

随手写下来一堆运算符,看起来实现会很复杂?其实不会有多复杂。在下一篇文章里面,我们会讨论如何设计一个运算符接口,然后逐一实现这些运算符。
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn