Created
February 16, 2022 18:29
-
-
Save rodrigodiasnoronha/f074862e7b91185cf7604b5e7a51c8f2 to your computer and use it in GitHub Desktop.
Verificar porcentagem de similaridade entre 2 strings
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
| /** | |
| * | |
| * Retorna em porcentagem a similaridade entre dois campos | |
| * Os valores podem vim de 0 até 1, onde 1 é 100% igual | |
| * | |
| */ | |
| export const retornarSimilaridadeEntreCampos = (value1, value2) => { | |
| function similarity(s1, s2) { | |
| var longer = s1; | |
| var shorter = s2; | |
| if (s1.length < s2.length) { | |
| longer = s2; | |
| shorter = s1; | |
| } | |
| var longerLength = longer.length; | |
| if (longerLength == 0) { | |
| return 1.0; | |
| } | |
| return (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength); | |
| } | |
| function editDistance(s1, s2) { | |
| s1 = s1.toLowerCase(); | |
| s2 = s2.toLowerCase(); | |
| var costs = new Array(); | |
| for (var i = 0; i <= s1.length; i++) { | |
| var lastValue = i; | |
| for (var 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]; | |
| } | |
| return similarity(value1, value2); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment