-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
suggestCollector.js
211 lines (211 loc) · 8.21 KB
/
suggestCollector.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isSuggestionResult = exports.impersonateCollector = exports.suggestionCollector = exports.defaultSuggestionCollectorOptions = exports.compSuggestionResults = exports.DEFAULT_COMPOUNDED_WORD_SEPARATOR = void 0;
const __1 = require("..");
const weightedMaps_1 = require("../distance/weightedMaps");
const timer_1 = require("../utils/timer");
const util_1 = require("../utils/util");
const walker_1 = require("./walker");
const defaultMaxNumberSuggestions = 10;
const BASE_COST = 100;
const MAX_NUM_CHANGES = 5;
const MAX_COST_SCALE = 0.5;
// max allowed cost scale should be a bit over 50% to allow for suggestions to short words, but not too high to have too many suggestions.
const MAX_ALLOWED_COST_SCALE = 1.03 * MAX_COST_SCALE;
const collator = new Intl.Collator();
// This is a bit broken, it was supposed to also include JOIN_SEPARATOR (`+`)
// Add it back later.
const regexSeparator = new RegExp(`[${(0, util_1.regexQuote)(walker_1.WORD_SEPARATOR)}]`, 'g');
const wordLengthCost = [0, 50, 25, 5, 0];
const EXTRA_WORD_COST = 5;
exports.DEFAULT_COMPOUNDED_WORD_SEPARATOR = '∙';
/** time in ms */
const DEFAULT_COLLECTOR_TIMEOUT = 1000;
const symStopProcessing = Symbol('Collector Stop Processing');
// comparison function for Suggestion Results.
function compSuggestionResults(a, b) {
return a.cost - b.cost || a.word.length - b.word.length || collator.compare(a.word, b.word);
}
exports.compSuggestionResults = compSuggestionResults;
exports.defaultSuggestionCollectorOptions = Object.freeze({
numSuggestions: defaultMaxNumberSuggestions,
filter: () => true,
changeLimit: MAX_NUM_CHANGES,
includeTies: false,
ignoreCase: true,
timeout: DEFAULT_COLLECTOR_TIMEOUT,
weightMap: undefined,
compoundSeparator: '',
compoundMethod: undefined,
});
function suggestionCollector(wordToMatch, options) {
const { filter = () => true, changeLimit = MAX_NUM_CHANGES, includeTies = false, ignoreCase = true, timeout = DEFAULT_COLLECTOR_TIMEOUT, weightMap, compoundSeparator = exports.defaultSuggestionCollectorOptions.compoundSeparator, } = options;
const numSuggestions = Math.max(options.numSuggestions, 0) || 0;
const numSugToHold = weightMap ? numSuggestions * 2 : numSuggestions;
const sugs = new Map();
let maxCost = BASE_COST * Math.min(wordToMatch.length * MAX_ALLOWED_COST_SCALE, changeLimit);
const useSeparator = compoundSeparator ||
(weightMap ? exports.DEFAULT_COMPOUNDED_WORD_SEPARATOR : exports.defaultSuggestionCollectorOptions.compoundSeparator);
const fnCleanWord = !useSeparator || useSeparator === compoundSeparator ? (w) => w : (0, util_1.replaceAllFactory)(useSeparator, '');
if (useSeparator && weightMap) {
(0, weightedMaps_1.addDefToWeightMap)(weightMap, { map: useSeparator, insDel: 50 });
}
const genSuggestionOptions = (0, util_1.clean)({
changeLimit,
ignoreCase,
compoundMethod: options.compoundMethod,
compoundSeparator: useSeparator,
});
let timeRemaining = timeout;
function dropMax() {
if (sugs.size < 2 || !numSuggestions) {
sugs.clear();
return;
}
const sorted = [...sugs.values()].sort(compSuggestionResults);
let i = numSugToHold - 1;
maxCost = sorted[i].cost;
for (; i < sorted.length && sorted[i].cost <= maxCost; ++i) {
/* empty */
}
for (; i < sorted.length; ++i) {
sugs.delete(sorted[i].word);
}
}
function adjustCost(sug) {
const words = sug.word.split(regexSeparator);
const extraCost = words.map((w) => wordLengthCost[w.length] || 0).reduce((a, b) => a + b, 0) +
(words.length - 1) * EXTRA_WORD_COST;
return { word: sug.word, cost: sug.cost + extraCost, isPreferred: sug.isPreferred };
}
function collectSuggestion(suggestion) {
const { word, cost, isPreferred } = adjustCost(suggestion);
if (cost <= maxCost && filter(suggestion.word, cost)) {
const known = sugs.get(word);
if (known) {
known.cost = Math.min(known.cost, cost);
known.isPreferred = known.isPreferred || isPreferred;
}
else {
sugs.set(word, { word, cost, isPreferred });
if (cost < maxCost && sugs.size > numSugToHold) {
dropMax();
}
}
}
return maxCost;
}
/**
* Collection suggestions from a SuggestionIterator
* @param src - the SuggestionIterator used to generate suggestions.
* @param timeout - the amount of time in milliseconds to allow for suggestions.
*/
function collect(src, timeout, filter) {
let stop = false;
timeout = timeout ?? timeRemaining;
timeout = Math.min(timeout, timeRemaining);
if (timeout < 0)
return;
const timer = (0, timer_1.createTimer)();
let ir;
while (!(ir = src.next(stop || maxCost)).done) {
if (timer.elapsed() > timeout) {
stop = symStopProcessing;
}
const { value } = ir;
if (!value)
continue;
if (isSuggestionResult(value)) {
if (!filter || filter(value.word, value.cost)) {
collectSuggestion(value);
}
continue;
}
}
timeRemaining -= timer.elapsed();
}
function cleanCompoundResult(sr) {
const { word, cost } = sr;
const cWord = fnCleanWord(word);
if (cWord !== word) {
return {
word: cWord,
cost,
compoundWord: word,
isPreferred: undefined,
};
}
return { ...sr };
}
function suggestions() {
if (numSuggestions < 1 || !sugs.size)
return [];
const NF = 'NFD';
const nWordToMatch = wordToMatch.normalize(NF);
const rawValues = [...sugs.values()];
const values = weightMap
? rawValues.map(({ word, isPreferred }) => ({
word,
cost: (0, __1.editDistanceWeighted)(nWordToMatch, word.normalize(NF), weightMap, 110),
isPreferred,
}))
: rawValues;
const sorted = values.sort(compSuggestionResults).map(cleanCompoundResult);
let i = Math.min(sorted.length, numSuggestions) - 1;
const limit = includeTies ? sorted.length : Math.min(sorted.length, numSuggestions);
const iCost = sorted[i].cost;
const maxCost = Math.min(iCost, weightMap ? changeLimit * BASE_COST - 1 : iCost);
for (i = 1; i < limit && sorted[i].cost <= maxCost; ++i) {
// loop
}
sorted.length = i;
return sorted;
}
const collector = {
collect,
add: function (suggestion) {
collectSuggestion(suggestion);
return this;
},
get suggestions() {
return suggestions();
},
get maxCost() {
return maxCost;
},
get word() {
return wordToMatch;
},
get maxNumSuggestions() {
return numSuggestions;
},
get changeLimit() {
return changeLimit;
},
includesTies: includeTies,
ignoreCase,
symbolStopProcessing: symStopProcessing,
genSuggestionOptions,
};
return collector;
}
exports.suggestionCollector = suggestionCollector;
/**
* Impersonating a Collector, allows searching for multiple variants on the same word.
* The collection is still in the original collector.
* @param collector - collector to impersonate
* @param word - word to present instead of `collector.word`.
* @returns a SuggestionCollector
*/
function impersonateCollector(collector, word) {
const r = Object.create(collector);
Object.defineProperty(r, 'word', { value: word, writable: false });
return r;
}
exports.impersonateCollector = impersonateCollector;
function isSuggestionResult(s) {
const r = s;
return r?.cost !== undefined && r.word != undefined;
}
exports.isSuggestionResult = isSuggestionResult;
//# sourceMappingURL=suggestCollector.js.map