I am writing an algorithm that, given a word spoken by the user, finds the most similar variant of that word in a given array. For example let the given array be:
const givenArr = ["foo","bar","foobar"];
and my "spoken" word right now used for testing:
const currText = "foo"
Basically, I want to match the currText with an element in the givenArr. This example is simple, the words are the same. But the user speech and the overall reception may vary, so "foo" may be received as only "fo" or "for" thus the words don't match so simply. This is my current solution:
givenArr.forEach((word) => {
if (currText.length <= word.length + 1) {
let foundMatch = 0;
let buffWord = currText;
word = word.split('');
word.forEach((char) => {
if (buffWord.includes(char)) {
foundMatch++;
buffWord = buffWord.slice(1);
}
});
if (foundMatch >= word.length - 1) {
let finalText = word.join(''); // get the fullword back.
console.log(finalText)
}
}
});
The way it works is by checking how many chars are similar in every word in givenArr with currText. If most of them correlate then I found the closest element. I've manually tested it with my needed array (which is not big, maximum 10 words ) and it works, but the algorithm looks ugly and I belive is slow ( it takes somewhere between 2 - 3 ms to find it ). How can I make this more efficient?