Last active
April 24, 2017 14:55
-
-
Save liesislukas/0199c5d1868b31c0912b61a517f1d3c8 to your computer and use it in GitHub Desktop.
normalized levenshtein to get % of match between 2 strings. 1 = 100%, 0 = 0%
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
let levenshtein = function (str1, str2) { | |
let current = [], prev, value; | |
for (let i = 0; i <= str2.length; i++) | |
for (let j = 0; j <= str1.length; j++) { | |
if (i && j) | |
if (str1.charAt(j - 1) === str2.charAt(i - 1)) | |
value = prev; | |
else | |
value = Math.min(current[j], current[j - 1], prev) + 1; | |
else | |
value = i + j; | |
prev = current[j]; | |
current[j] = value; | |
} | |
return current.pop(); | |
}; | |
// 0 = 0% 1 = 100% match | |
export default function ({a, b}) { | |
let str1 = a; | |
let str2 = b; | |
if (str1 === null && str2 === null) return 0; | |
if (str1 === null || str2 === null) return 0; | |
str1 = String(str1); | |
str2 = String(str2); | |
let distance = levenshtein(str1, str2); | |
if (str1.length > str2.length) { | |
return 1 - distance / str1.length; | |
} else { | |
return 1 - distance / str2.length; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
extracted most of the code from https://github.com/Glench/fuzzyset.js/blob/master/lib/fuzzyset.js lib