Last active
March 28, 2022 18:45
-
-
Save dacastro4/ab117e91276e343c85ceff893abe8eed to your computer and use it in GitHub Desktop.
Word Similarity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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