Skip to content

Commit 619fbee

Browse files
committed
Optimized check word function.
1 parent 2f28afc commit 619fbee

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

src/model/Game.ts

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { LetterState, type Letter } from "./Letter";
22
import { words as wordsEN } from "../../words/words-en.json";
3-
import { words as wordsNL } from "../../words/words-debug.json";
4-
import { words as wordsNAL } from "../../words/words-nl.json";
3+
import { words as wordsNL } from "../../words/words-nl.json";
54

65
export type Language = "nl" | "en";
76

@@ -29,29 +28,24 @@ export function checkWord(game: Game, guessedWord: string): Game {
2928
if (finalWordLetters[index] == letter) {
3029
letterState = LetterState.CORRECT;
3130
} else {
32-
// If not, get all positions of the same, remaning letters.
33-
// This is needed to determine if the letter is in the word or not.
34-
const lettersIndexes = finalWordLetters.flatMap((fletter, index) =>
35-
fletter == letter ? [index] : [],
31+
// If not, get all positions of the same, misplaced letters.
32+
const lettersIndexes = finalWordLetters.flatMap((fletter, findex) =>
33+
fletter == letter && finalWordLetters[findex] != letters[findex]
34+
? [findex]
35+
: [],
3636
);
3737

38-
for (const letterIndex in lettersIndexes) {
39-
if (finalWordLetters[letterIndex] == letters[letterIndex]) {
40-
continue;
41-
}
42-
43-
// Get the count of other letters that are placed incorrectly in the word.
44-
const letterCount = finalWordLetters.filter(
45-
(l, index) =>
46-
l == letter && finalWordLetters[index] != letters[index],
47-
).length;
38+
for (let i = 0; lettersIndexes.length; i++) {
39+
// Get how many IN_WORD marks already have been made for this letter.
40+
// When all misplaced letters have already been marked, this letter is not
41+
// marked as IN_WORD anymore.
4842
const hintedLetterCount = hintedLetters.get(letter);
4943

50-
// When the hitedLetterCount is higher or equal then the letterCount, all in word
51-
// positions have been marked (or are correct).
44+
// When the hitedLetterCount is higher or equal then the letterCount, all IN_WORD
45+
// positions for this have been marked (or are correctly placed).
5246
if (
5347
hintedLetterCount != undefined &&
54-
hintedLetterCount >= letterCount
48+
hintedLetterCount >= lettersIndexes.length
5549
) {
5650
continue;
5751
}

0 commit comments

Comments
 (0)