Skip to content

Instantly share code, notes, and snippets.

@dacastro4
Last active March 28, 2022 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacastro4/ab117e91276e343c85ceff893abe8eed to your computer and use it in GitHub Desktop.
Save dacastro4/ab117e91276e343c85ceff893abe8eed to your computer and use it in GitHub Desktop.
Word Similarity
const editDistance = (s1, s2) => {
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
const costs = [];
for (let i = 0; i <= s1.length; i++) {
let lastValue = i;
for (let j = 0; j <= s2.length; j++) {
if (i === 0) {
costs[j] = j;
} else {
if (j > 0) {
var newValue = costs[j - 1];
if (s1.charAt(i - 1) !== s2.charAt(j - 1)) {
newValue = Math.min(Math.min(newValue, lastValue), costs[j]) + 1;
}
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
}
if (i > 0) {
costs[s2.length] = lastValue;
}
}
return costs[s2.length];
}
export default (s1, s2) => {
let longer = s1;
let shorter = s2;
if (s1.length < s2.length) {
longer = s2;
shorter = s1;
}
const longerLength = longer.length;
if (longerLength === 0) {
return 1.0;
}
return (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment