-
Notifications
You must be signed in to change notification settings - Fork 1
/
select.js
40 lines (35 loc) · 945 Bytes
/
select.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
// of several indexes available,
// select the one most suitable for a given query.
// select the index that matches the most exact fields in the query
// starting from the left, then moving on to range fields.
var Q = require('map-filter-reduce/util')
var u = require('./util')
function _max (ary, score) {
var j = -1; var M = 0
for (var i = 0; i < ary.length; i++) {
var m = score(ary[i])
if (m > M) {
M = m; j = i
}
}
return ary[j]
}
module.exports = function select (indexes, query) {
function score (k) {
var v = u.get(k, query)
return u.has(k, query) ? (
Q.isExact(v) ? 3
: Q.isRange(v) ? 2
: 1
) : 0
}
return _max(indexes, function (index) {
var s = 0; var _s
for (var i = 0; i < index.value.length; i++) {
_s = score(index.value[i])
if (!_s) return s // stop counting when one thing doesn't match
s = s * s + _s
}
return s
})
}