JSFiddle - React, Tailwind, and code Playground
by Kelvin Russell
HTML
<input type="text" id="searchField" placeholder="Type here">
<div id="results" style="display:none;"></div>
CSS
* { font: 18px "Lucida Grande", Helvetica, Arial, sans-serif; }
body { padding: 30px; }
#results { width: 10em; border: 1px solid #ccc; padding: 5px; }
p { margin: 0; padding: 0; }
p span { color: #aba; }
JavaScript
$(function(){
// Cache important elements and values
var $searchField = $('#searchField'),
$results = $('#results'),
shortlist,
thresholdDistance;
// Do as little as possible in the keyboard event handler
$searchField.on('keyup', function(){
console.log("help")
shortlist = [];
thresholdDistance = 100;
// Run through the full dictionary just once,
// storing just the best N we've seen so far
for (var i=0; i<dictionarySize; i++) {
var dist = edit_distance(this.value, dictionary[i]);
if (dist < thresholdDistance) {
shortlist.unshift({
word: dictionary[i],
distance: dist
});
if (shortlist.length > 1) {
shortlist.pop();
thresholdDistance = shortlist[0].distance;
}
}
}
// Finally, format and show the suggestions to the user
$results.html('<p>' + shortlist[0].word + '</p>').show();
});
// Helper function: Levenshtein distance
var edit_distance = function(s1, s2) {
// Auxiliary 2D array
var arr = new Array(s1.length+1);
for(var i=0 ; i<s1.length+1 ; i++)
arr[i] = new Array(s2.length+1);
// Algorithm
for(var i=0 ; i<=s1.length ; i++)
for(var j=0 ; j<=s2.length ; j++)
arr[i][j] = 0;
for(var i=0 ; i<=s1.length ; i++)
arr[i][0] = i;
for(var i=0 ; i<=s2.length ; i++)
arr[0][i] = i;
for(var i=1 ; i<=s1.length ; i++)
for(var j=1 ; j<=s2.length ; j++)
arr[i][j] = Math.min(arr[i-1][j-1] + (s1.charAt(i-1)==s2.charAt(j-1) ? 0 : 1), arr[i-1][j]+1, arr[i][j-1]+1);
// Final answer
return arr[s1.length][s2.length].toString(10);
};
});
// Pre-generate twelve thousand...