-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
69 lines (62 loc) · 2.19 KB
/
index.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
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
function getStringPool(string, options) {
var cleanedString = (options.caseInsensitive ? string.toLowerCase() : string).trim();
var splitTokenRegex = new RegExp(options.splitByTokens.join('|'));
return cleanedString.split(splitTokenRegex).filter(function(i) { return i; });
}
function getSuggestedMatches(sentences, query) {
return (
sentences
.map(function(sentence) {
return {
sentence: sentence,
matchStrength: partialMatch.getQueryMatchStrength(sentence, query),
};
})
.filter(function(item) { return item.matchStrength; })
.sort(function(item1, item2) { return item2.matchStrength - item1.matchStrength; })
.map(function(item) { return item.sentence; })
);
}
module.exports = function partialMatchFactory(config) {
var defaultOptions = {
caseInsensitive: true,
splitByTokens: [' '],
};
var options = {
caseInsensitive: (config || {}).hasOwnProperty('caseInsensitive') ? config.caseInsensitive : defaultOptions.caseInsensitive,
splitByTokens: (
[]
.concat(defaultOptions.splitByTokens)
.concat(config.splitByTokens.map(escapeRegExp) || [])
),
};
return {
getQueryMatchStrength: function(sentence, query) {
var sentenceStringPool = getStringPool(sentence, options);
var queryStringPool = getStringPool(query, options);
return sentenceStringPool.reduce(function(totalScore, str) {
return queryStringPool.reduce(function(score, qStr) {
return score + (str.indexOf(qStr) === 0 ? 1 : 0);
}, totalScore);
}, 0);
},
getSuggestedMatches: function(sentences, query) {
var self = this;
return (
sentences
.map(function(sentence) {
return {
sentence: sentence,
matchStrength: self.getQueryMatchStrength(sentence, query),
};
})
.filter(function(item) { return item.matchStrength; })
.sort(function(item1, item2) { return item2.matchStrength - item1.matchStrength; })
.map(function(item) { return item.sentence; })
);
},
};
}