Thanks to Basilicum and Jason Nichols, as well as Mike and Andrew for comments, it really helped me finish the algorithm. I come up with my solution for brute force O(n^3) if someone comes across this issue with the same problem.
Anyone is invited to play the violin to improve it.
Algorithm
function fuzzyMatch(needle,accurancy,haystack) { function strcmpshift(a,b,shift) { var match=0, len=Math.min(a.length,b.length); for(var i in a) if(a[i]==b[+i+shift]) ++match; return match; } function strcmp(a,b) { for(var i=0,max=0,now; i<b.length; ++i) { now = strcmpshift(a,b,i); if(now>max) max = now; } return max; } var word,best=accurancy-1,step,item; for(var i in haystack) { item = haystack[i]; step = Math.max(strcmp(item,needle),strcmp(needle,item)); if(step<=best) continue; best=step, word=item; }; return word; }
Example
var word = "rotation"; var commands = ["notable","tattoo","onclick","statistically"];
source share