I'm making a word guessing application (like Wordle).
Let's assume I have a predefined word
let predefinedWord = "apple";
I want to make a function to compare with the predefined word.
const compare = (word) => {
// compare the guess with the predefined word apple
}
let myGuess = "alley"
const result = compare(myGuess); // compare apple with alley
// return
// ["Matched", "Included", "Included", "Included", "Not Matched"]
How can I make the function like this?
If the word length is as short as in wordle, a direct approach works well:
let predefinedWord = "apple";
let predefArr = predefinedWord.split('');
const compare = (predef,word) => {
return word
.split('')
.map( (letter,i) => {
if (predef[i] === letter) return "Matched";
if (predef.includes(letter)) return "Included";
return "Not Matched"
});
}
let myGuess = "alley"
const result = compare(predefArr, myGuess); // compare apple with alley
// return
// ["Matched", "Included", "Included", "Included", "Not Matched"]
console.log(result)
EDIT: This answers the original question:
let myGuess = "alley" const result = compare(myGuess); // compare apple with alley // return // ["Matched", "Included", "Included", "Included", "Not Matched"]
How can I make the function like this?
And it is not the behaviour of the game wordle
const compare = (word) => {
let result = [];
for(let i=0;i<word.length;i++){
if(predefinedWord.includes(word[i])){
result.push(predefinedWord.indexOf(word[i]) === i?"Matched":"Included")
}else{
result.push("Not Matched")
}
}
return result;
}
function comparisonhint(secret, guess) {
try {
const secretArr = secret.split('');
const guessArr = guess.split('');
if (secretArr.length !== guessArr.length) {
throw 'Secret and Guess must be same length.'
}
const hintArr = guessArr.map((letter, i) => {
return secretArr[i] == letter ? '✅' : secretArr.includes(letter) ? '🤏' : '❌';
});
return hintArr.join('');
} catch (err) {
console.error(err);
return err;
}
}
const hint = comparisonhint('words', 'guess');
console.log(hint);