Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:42
Show Gist options
  • Save rfprod/b44ab3847f05616d973f5e13a914a391 to your computer and use it in GitHub Desktop.
Save rfprod/b44ab3847f05616d973f5e13a914a391 to your computer and use it in GitHub Desktop.
Word Suggestion Service
function WordSuggestionService(words) {
this.words = words;
this.levenshtein = function(a, b) {
// special cases
if (a === b) { return 0; }
if (a === '') { return b.length; }
if (b === '') { return a.length; }
// determine longer string
let short = (a.length <= b.length) ? a : b;
let long = (a.length <= b.length) ? b : a;
// init vectors
let vector1 = [];
let vector2 = [];
vector2.length = long.length + 1;
for (let i = 0, max = long.length; i <= max; i++) { vector1.push(i); } // prefill vector1
for (let i = 0, iMax = short.length; i < iMax; i++) {
// vector2 - current distance from previous row
vector2[0] = i + 1;
for (let j = 0, jMax = long.length; j < jMax; j++) {
const increment = (short[i] === long[j]) ? 0 : 1;
vector2[j + 1] = Math.min(vector2[j] + 1, vector1[j + 1] + 1, vector1[j] + increment);
}
// copy vector2 to vector1 for next iteration
vector2.forEach((item, index) => vector1[index] = item);
}
return vector2[long.length]; // return last element of vector2
}
}
WordSuggestionService.prototype.suggest = function(term) {
let diff = [];
this.words.forEach(word => {
diff.push(this.levenshtein(term, word));
});
const minIndex = diff.indexOf(Math.min(...diff));
return this.words[minIndex];
}
const service = new WordSuggestionService(['javascript', 'java', 'ruby', 'php', 'python', 'coffeescript']);
const suggestion = service.suggest('heaven'); // java

Word Suggestion Service

Utilizes Levenshtein Distance algorythm to suggest a most similar word to the provided term. The service uses a words dictionary provided as a parameter on service instantiation new WordSuggestionService(['javascript', 'java', 'ruby', 'php', 'python', 'coffeescript']). The service's instance method suggest('heaven') returns a suggestion.

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment