wordle-clone/site/assets/scripts/models/words.js

65 lines
1.6 KiB
JavaScript
Raw Permalink Normal View History

2025-01-24 22:45:55 +00:00
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;
2025-01-25 00:30:04 +00:00
this._pattern = null;
2025-01-25 00:52:07 +00:00
// this._currentWord = null;
// this._progressionState=
2025-01-24 22:45:55 +00:00
}
isWord(word) {
let list = this._wordData.words[word.length.toString()];
if (!list) {
return false;
}
return binSearch(list, word);
}
2025-01-25 00:52:07 +00:00
async getCurrentWord(prog) {
2025-01-24 22:45:55 +00:00
let words = await this._fetchAllWordsIfNecessary();
2025-01-25 00:30:04 +00:00
2025-01-25 00:52:07 +00:00
let wordLengthKey = prog.wordLength + "";
let wordIndex = prog.wordIndex[wordLengthKey];
let idx = this._pattern.index[wordLengthKey][wordIndex];
2025-01-24 22:45:55 +00:00
2025-01-25 00:52:07 +00:00
return words.words[wordLengthKey][idx];
2025-01-24 22:45:55 +00:00
}
2025-01-25 00:52:07 +00:00
// async nextWord() {
// if (this._currentWord >= this._words.length - 1) {
// return false;
// }
//
// this._currentWord += 1;
// return true;
// }
2025-01-24 22:45:55 +00:00
async _fetchAllWordsIfNecessary() {
if (this._wordData) {
return this._wordData;
}
2025-01-25 00:30:04 +00:00
this._wordData = await (await fetch("/assets/data/words.json")).json();
this._pattern = await (await fetch("/assets/data/shuffle_pattern.json")).json();
2025-01-24 22:45:55 +00:00
return this._wordData;
}
}