-
Notifications
You must be signed in to change notification settings - Fork 6
/
expression.js
118 lines (95 loc) · 2.44 KB
/
expression.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
var ReParse = require('reparse').ReParse;
// --------------- grammar bits -------------------
function expr() {
return this.chainl1(term, disjunction);
}
function term() {
return this.chainl1(notFactor, conjunction);
}
function notFactor() {
return this.choice(negation, factor);
}
function factor() {
return this.choice(group, phrase, word);
}
function group() {
return this.between(/^\(/, /^\)/, expr);
}
function phrase() {
return this.between(/^\"/, /^\"/, words);
}
function words() {
return this.many1(word).join(' ');
}
function word() {
return this.match(/^[#@_\-'&!\w\dàèìòùáéíóúäëïöüâêîôûçßåøñœæ]+/i).toString();
}
function notop() {
return this.match(/^NOT/i).toUpperCase();
}
function negation() {
return this.seq(notop, notFactor).slice(1);
}
function conjunction() {
return OPTREES[this.match(/^AND/i).toUpperCase()];
}
function disjunction() {
return OPTREES[this.match(/^OR/i).toUpperCase()];
}
var OPTREES = {
'AND': function(a,b) { return [ 'AND', a, b ] },
'OR': function(a,b) { return [ 'OR', a, b ] }
};
// --------------- test strings -------------------
function evalTree(tree, text) {
if (!Array.isArray(tree)) {
//return text.toLowerCase().indexOf(tree.toLowerCase()) >= 0;
// TODO: cache these regexps?
return new RegExp("\\b"+tree+"\\b", "i").test(text);
}
var op = tree[0];
if (op == 'OR') {
return evalTree(tree[1], text) || evalTree(tree[2], text);
}
else if (op == 'AND') {
return evalTree(tree[1], text) && evalTree(tree[2], text);
}
else if (op == 'NOT') {
return !evalTree(tree[1], text);
}
}
// --------------- collect terms -------------------
function flattenTree(tree) {
// TODO: unique leaves, sorted?
return collectLeaves(tree, [], true);
}
function collectLeaves(tree, leaves, notnot) {
if (!Array.isArray(tree)) {
if (notnot) {
leaves.push(tree);
}
}
else {
if (tree[0] == "NOT") {
notnot = !notnot;
}
// i = 1 to skip AND/OR
for (var i = 1; i < tree.length; i++) {
collectLeaves(tree[i], leaves, notnot);
}
}
return leaves;
}
// --------------- public interface -------------------
function Expression(query) {
this.tree = new ReParse(query, true).start(expr);
}
Expression.prototype = {
flatten: function() {
return flattenTree(this.tree);
},
test: function(text) {
return evalTree(this.tree, text);
}
}
module.exports = Expression;