forked from aralejs/autocomplete
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter.js
More file actions
91 lines (77 loc) · 1.96 KB
/
Copy pathfilter.js
File metadata and controls
91 lines (77 loc) · 1.96 KB
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
var $ = require('jquery');
var Filter = {
'default': function (data) {
return data;
},
'startsWith': function (data, query) {
query = query || '';
var result = [],
l = query.length,
reg = new RegExp('^' + escapeKeyword(query));
if (!l) return [];
$.each(data, function (index, item) {
var a, matchKeys = [item.value].concat(item.alias);
// 匹配 value 和 alias 中的
while (a = matchKeys.shift()) {
if (reg.test(a)) {
// 匹配和显示相同才有必要高亮
if (item.label === a) {
item.highlightIndex = [
[0, l]
];
}
result.push(item);
break;
}
}
});
return result;
},
'stringMatch': function (data, query) {
query = query || '';
var result = [],
l = query.length;
if (!l) return [];
$.each(data, function (index, item) {
var a, matchKeys = [item.value].concat(item.alias);
// 匹配 value 和 alias 中的
while (a = matchKeys.shift()) {
if (a.indexOf(query) > -1) {
// 匹配和显示相同才有必要高亮
if (item.label === a) {
item.highlightIndex = stringMatch(a, query);
}
result.push(item);
break;
}
}
});
return result;
}
};
module.exports = Filter;
// 转义正则关键字
var keyword = /(\[|\[|\]|\^|\$|\||\(|\)|\{|\}|\+|\*|\?|\\)/g;
function escapeKeyword(str) {
return (str || '').replace(keyword, '\\$1');
}
function stringMatch(matchKey, query) {
var r = [],
a = matchKey.split('');
var queryIndex = 0,
q = query.split('');
for (var i = 0, l = a.length; i < l; i++) {
var v = a[i];
if (v === q[queryIndex]) {
if (queryIndex === q.length - 1) {
r.push([i - q.length + 1, i + 1]);
queryIndex = 0;
continue;
}
queryIndex++;
} else {
queryIndex = 0;
}
}
return r;
}