-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.mjs
41 lines (36 loc) · 1.33 KB
/
index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* Copyright © Michael Chan, 2022, MIT License */
/**
* Assess the correctness of a guess word against an answer word.
*
* @param answer {string} - The answer word
* @param guess {string} - The guess word
* @returns {[string, "correct" | "present" | "absent"][]} An array of tuples containing the letter and its relative precision
*/
export default function assess(answer, guess = "") {
if (typeof answer !== "string" || typeof guess !== "string") {
throw new TypeError("Inputs must be a string.");
}
// build a zipped array from answer to ensure the right array size
let zippedLetters = Array.from(answer, (_, i) => [answer[i], guess[i]]);
let availableLetterPool = zippedLetters.reduce(
(accumulator, [answerLetter, guessLetter]) =>
answerLetter === guessLetter
? accumulator
: {
...accumulator,
[answerLetter]: accumulator[answerLetter] + 1 || 1,
},
{}
);
let result = zippedLetters.map(([answerLetter, guessLetter]) => {
if (guessLetter === answerLetter) {
return [guessLetter, "correct"];
}
if (answer.includes(guessLetter) && availableLetterPool[guessLetter]) {
availableLetterPool[guessLetter] = availableLetterPool[guessLetter] - 1;
return [guessLetter, "present"];
}
return [guessLetter, "absent"];
});
return result;
}