/
custom-selector-helper.js
85 lines (73 loc) · 2.15 KB
/
custom-selector-helper.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
exports.parseparams = function (params) {
var query = params['query'],
ids, start, count;
try {
ids = params['ids'].split(',') || []
} catch (e) {
log.warning('Invalid parameter ids: %s, using []', params['ids']);
ids = [];
}
try {
start = Math.max(parseInt(params['start']) || 0, 0);
} catch (e) {
log.warning('Invalid parameter start: %s, using 0', params['start']);
start = 0;
}
try {
count = Math.max(parseInt(params['count']) || 15, 0);
} catch (e) {
log.warning('Invalid parameter count: %s, using 15', params['count']);
count = 15;
}
return {
query: query,
ids: ids,
start: start,
end: start + count,
count: count
}
};
/**
* Create results filtered by params
* @param items
* @param params = {
query: string,
ids: [...],
start: number,
end: number,
count: number
}
* @param total
* @returns body = {
total: number,
count: number,
hits: [...]
}
*/
exports.createresults = function (items, params, total) {
var body = {};
var hitCount = 0, include;
body.hits = items.sort(function (hit1, hit2) {
if (!hit1 || !hit2) {
return !!hit1 ? 1 : -1;
}
return hit1.displayName.localeCompare(hit2.displayName);
}).filter(function (hit) {
include = true;
if (!!params.ids && params.ids.length > 0) {
include = params.ids.some(function (id) {
return id == hit.id;
});
} else if (!!params.query && params.query.trim().length > 0) {
var qRegex = new RegExp(params.query, 'i');
include = qRegex.test(hit.displayName) || qRegex.test(hit.description) || qRegex.test(hit.id);
}
if (include) {
hitCount++;
}
return include && hitCount > params.start && hitCount <= params.end;
});
body.count = Math.min(params.count, body.hits.length);
body.total = params.query ? hitCount : (total || items.length);
return body;
};