UNPKG

1.79 kBJavaScriptView Raw
1var AND_REGEXP = /^\s+and\s+(.*)/i
2var OR_REGEXP = /^(?:,\s*|\s+or\s+)(.*)/i
3
4function flatten(array) {
5 if (!Array.isArray(array)) return [array]
6 return array.reduce(function (a, b) {
7 return a.concat(flatten(b))
8 }, [])
9}
10
11function find(string, predicate) {
12 for (var n = 1, max = string.length; n <= max; n++) {
13 var parsed = string.substr(-n, n)
14 if (predicate(parsed, n, max)) {
15 return string.slice(0, -n)
16 }
17 }
18 return ''
19}
20
21function matchQuery(all, query) {
22 var node = { query: query }
23 if (query.indexOf('not ') === 0) {
24 node.not = true
25 query = query.slice(4)
26 }
27
28 for (var name in all) {
29 var type = all[name]
30 var match = query.match(type.regexp)
31 if (match) {
32 node.type = name
33 for (var i = 0; i < type.matches.length; i++) {
34 node[type.matches[i]] = match[i + 1]
35 }
36 return node
37 }
38 }
39
40 node.type = 'unknown'
41 return node
42}
43
44function matchBlock(all, string, qs) {
45 var node
46 return find(string, function (parsed, n, max) {
47 if (AND_REGEXP.test(parsed)) {
48 node = matchQuery(all, parsed.match(AND_REGEXP)[1])
49 node.compose = 'and'
50 qs.unshift(node)
51 return true
52 } else if (OR_REGEXP.test(parsed)) {
53 node = matchQuery(all, parsed.match(OR_REGEXP)[1])
54 node.compose = 'or'
55 qs.unshift(node)
56 return true
57 } else if (n === max) {
58 node = matchQuery(all, parsed.trim())
59 node.compose = 'or'
60 qs.unshift(node)
61 return true
62 }
63 return false
64 })
65}
66
67module.exports = function parse(all, queries) {
68 if (!Array.isArray(queries)) queries = [queries]
69 return flatten(
70 queries.map(function (block) {
71 var qs = []
72 do {
73 block = matchBlock(all, block, qs)
74 } while (block)
75 return qs
76 })
77 )
78}