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?
CodePudding user response:
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)
CodePudding user response:
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;
}