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

68 lines
1.8 KiB
JavaScript
Raw 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._dataVersion = null;
2025-01-24 22:45:55 +00:00
this._wordData = null;
this._otherWords = null;
2025-01-25 00:30:04 +00:00
this._pattern = null;
2025-01-24 22:45:55 +00:00
}
isWord(word) {
if (!this._wordData || !this._otherWords) {
2025-01-24 22:45:55 +00:00
return false;
}
return binSearch(this._wordData[word.length.toString()], word) ||
binSearch(this._otherWords[word.length.toString()], word);
2025-01-24 22:45:55 +00:00
}
async needToResetProgression(prog) {
await this._fetchAllWordsIfNecessary();
return !prog || !prog.shuffleId || this._dataVersion !== prog.shuffleId;
}
async getPattenShuffleID() {
return this._dataVersion;
}
2025-01-24 22:45:55 +00:00
2025-01-25 00:52:07 +00:00
async getCurrentWord(prog) {
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[wordLengthKey][wordIndex];
2025-01-24 22:45:55 +00:00
return this._wordData[wordLengthKey][idx];
2025-01-24 22:45:55 +00:00
}
async _fetchAllWordsIfNecessary() {
if (this._wordData) {
return this._wordData;
}
let data = await (await fetch("/assets/data/data.json")).json();
this._dataVersion = data["versionId"];
this._wordData = data["guessWords"];
this._otherWords = data["otherWords"];
this._pattern = data["shufflePattern"];
2025-01-24 22:45:55 +00:00
}
}