65 lines
1.7 KiB
JavaScript
65 lines
1.7 KiB
JavaScript
function binSearch(list, word) {
|
|
let first = 0;
|
|
let last = list.length;
|
|
|
|
for (;;) {
|
|
let ptr = (first + (last - first) / 2) | 0;
|
|
if (list[ptr] === word) {
|
|
return true;
|
|
} else if (last - first <= 1) {
|
|
return false;
|
|
} else if (list[ptr] > word) {
|
|
last = ptr;
|
|
} else if (list[ptr] < word) {
|
|
first = ptr;
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
export class WordSource {
|
|
constructor() {
|
|
this._wordData = null;
|
|
this._pattern = null;
|
|
// this._currentWord = null;
|
|
// this._progressionState=
|
|
}
|
|
|
|
isWord(word) {
|
|
let list = this._wordData.words[word.length.toString()];
|
|
if (!list) {
|
|
return false;
|
|
}
|
|
|
|
return binSearch(list, word);
|
|
}
|
|
|
|
async needToResetProgression(prog) {
|
|
await this._fetchAllWordsIfNecessary();
|
|
return !prog || !prog.shuffleId || this._pattern.id !== prog.shuffleId;
|
|
}
|
|
|
|
async getPattenShuffleID() {
|
|
return this._pattern.id;
|
|
}
|
|
|
|
async getCurrentWord(prog) {
|
|
let words = await this._fetchAllWordsIfNecessary();
|
|
|
|
let wordLengthKey = prog.wordLength + "";
|
|
let wordIndex = prog.wordIndex[wordLengthKey];
|
|
let idx = this._pattern.index[wordLengthKey][wordIndex];
|
|
|
|
return words.words[wordLengthKey][idx];
|
|
}
|
|
|
|
async _fetchAllWordsIfNecessary() {
|
|
if (this._wordData) {
|
|
return this._wordData;
|
|
}
|
|
|
|
this._wordData = await (await fetch("/assets/data/words.json")).json();
|
|
this._pattern = await (await fetch("/assets/data/shuffle_pattern.json")).json();
|
|
return this._wordData;
|
|
}
|
|
} |