-
Notifications
You must be signed in to change notification settings - Fork 546
/
matchSorter.js
66 lines (61 loc) · 1.66 KB
/
matchSorter.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
/**
* @param {string[]} matches - unordered list of matches.
* @param {...string} query - original query that generated matches
* @returns {string[]} matches sorted by estimated priority.
*
* matches that start with the first query component are prioritized.
* @example
* (["build:types", "test"], "t") -> ["test", "build:types"]
*
* Matches that contain a full word match with the query are prioritized.
* @example
* (["presigner", "signer"], "signer") -> ["signer", "presigner"]
*
* Shorter matches are prioritized.
*/
module.exports = function matchSorter(matches, ...query) {
return matches.sort((a, b) => {
a = a.name || a;
b = b.name || b;
let score = 0;
if (wholeWordMatch(a, ...query)) {
score -= 100;
}
if (wholeWordMatch(b, ...query)) {
score += 100;
}
if (wordInitialMatch(a, ...query)) {
score -= 10;
}
if (wordInitialMatch(b, ...query)) {
score += 10;
}
if (a.length < b.length) {
score -= 1;
}
if (a.length > b.length) {
score += 1;
}
return score;
});
};
/**
* @returns {boolean} subject has a word that starts with a query component.
*/
function wordInitialMatch(subject, ...query) {
const _words = words(subject);
return _words.filter((w) => undefined !== query.find((q) => w.startsWith(q))).length > 0;
}
/**
* @returns {boolean} subject has a whole word match with part of the query.
*/
function wholeWordMatch(subject, ...query) {
const _words = words(subject);
return _words.filter((w) => query.includes(w)).length > 0;
}
/**
* Splits the search subject into words.
*/
function words(subject) {
return subject.split(/:|\s+|-|_/);
}