Tidy up: define WordListModel in a IIFE so that it can have private constants.

This commit is contained in:
Eddie Antonio Santos 2019-01-18 13:07:55 -07:00
parent 2c8237c379
commit 89f9d8a2f1
No known key found for this signature in database
GPG key ID: DD411EA4D9509D87

View file

@ -29,33 +29,40 @@
*/
/**
* @class WordListModel
*
* Defines the word list model, or the unigram model.
* Unigram models throw away all preceding words, and search
* for the next word exclusively. As such, they can perform simple
* prefix searches within words, however they are not very good
* at predicting the next word.
*/
// TODO: define this in an IIFE.
LMLayerWorker.models.WordListModel = class WordListModel implements WorkerInternalModel {
private _wordlist: string[];
LMLayerWorker.models.WordListModel = (function () {
/** Upper bound on the amount of suggestions to generate. */
const MAX_SUGGESTIONS = 3;
constructor(_capabilities: Capabilities, wordlist: string[]) {
this._wordlist = wordlist;
}
return class WordListModel implements WorkerInternalModel {
private _wordlist: string[];
predict(transform: Transform, context: Context): Suggestion[] {
const MAX_SUGGESTIONS = 3;
// All text to the left of the cursor INCLUDING anything that has
// just been typed.
let leftContext = context.left || '';
let prefix = leftContext + (transform.insert || '');
let suggestions: Suggestion[] = [];
constructor(_capabilities: Capabilities, wordlist: string[]) {
this._wordlist = wordlist;
}
predict(transform: Transform, context: Context): Suggestion[] {
// All text to the left of the cursor INCLUDING anything that has
// just been typed.
let leftContext = context.left || '';
let prefix = leftContext + (transform.insert || '');
let suggestions: Suggestion[] = [];
// Naïve O(n) exhaustive search through the entire word
// list, up to the suggestion limit.
for (let word of this._wordlist) {
let suggestionPrefix = word.substr(0, prefix.length);
if (prefix !== suggestionPrefix) {
continue;
}
// Naïve O(n) exhaustive search through the entire word
// list, up to the suggestion limit.
for (let word of this._wordlist) {
let suggestionPrefix = word.substr(0, prefix.length);
if (prefix === suggestionPrefix) {
suggestions.push({
transform: {
// The left part of the word has already been entered.
@ -64,14 +71,14 @@ LMLayerWorker.models.WordListModel = class WordListModel implements WorkerIntern
},
displayAs: word,
});
// Do not exceed the limit on suggestions.
if (suggestions.length >= MAX_SUGGESTIONS) {
break;
}
}
// Do not exceed the limit on suggestions.
if (suggestions.length >= MAX_SUGGESTIONS) {
break;
}
return suggestions;
}
return suggestions;
}
}
};
}());