Skip to content

Instantly share code, notes, and snippets.

@liesislukas
Last active April 24, 2017 14:55
Show Gist options
  • Save liesislukas/0199c5d1868b31c0912b61a517f1d3c8 to your computer and use it in GitHub Desktop.
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%
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;
}
}
@liesislukas
Copy link
Author

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