Full-time web dev; JS lover since 2002; CSS fanatic. #CSSIsAwesome
I try to stay up with new web platform features. Web feature you don't understand? Tell me! I'll write an article!
He/him
/**
* Find the Levenshtein distance between two strings
* (see https://en.wikipedia.org/wiki/Levenshtein_distance)
* @param {String} a First string to compare
* @param {String} b Second string to compare
*/functionlev(a,b){const_step=(i,j)=>(Math.min(i,j)===0?Math.max(i,j):Math.min(_step(i-1,j)+1,_step(i,j-1)+1,_step(i-1,j-1)+(a[i-1]===b[j-1]?0:1)))return_step(a.length,b.length)}/**
* Find the most similar word in the dictionary to the provided word
* @param {String[]} dict Array of strings to use as dictionary
* @param {String} word Word to correct
*/functionfindMostSimilar(dict,word){const[,closest]=dict.reduce(([min,best],next)=>{constdist=lev(word,next)returndist<min?[dist,next]:[min,best]},[Infinity,''])returnclosest}
EDIT
Forgot to add testing code, so here's some test cases. (The test runner assumes that it's being run in the web console, by the way.)
// Testsconsta1=['cherry','pineapple','melon','strawberry','raspberry']consta2=['stars','mars','wars','codec','codewars']consta3=['javascript','java','ruby','php','python','coffeescript']consttestCases=[[a1,'strawbery','strawberry'],[a1,'berry','cherry'],[a2,'code','codec'],[a2,'starwars','stars'],[a3,'script','javascript'],[a3,'cofcript','coffeescript']]letcaseNum=1for(const[dict,input,expected]oftestCases){constoutput=findMostSimilar(dict,input)const[status,style]=(output===expected?['✔','color: green']:['❌','color: red'])console.log(`${caseNum++}: ${input} should match ${expected} %c${status}`,style)if(output!==expected){console.log(` returned ${output} instead`)}}
And here's the output when I run it in Chrome:
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Implemented the algorithm in the Wikipedia article for Levenshtein distance in JavaScript:
EDIT
Forgot to add testing code, so here's some test cases. (The test runner assumes that it's being run in the web console, by the way.)
And here's the output when I run it in Chrome: