levenshtein.js 731 B

1234567891011121314151617181920212223242526
  1. export function levenshtein(a, b) {
  2. if (a.length === 0)
  3. return b.length;
  4. if (b.length === 0)
  5. return a.length;
  6. const matrix = [];
  7. let i;
  8. for (i = 0; i <= b.length; i++) {
  9. matrix[i] = [i];
  10. }
  11. let j;
  12. for (j = 0; j <= a.length; j++) {
  13. matrix[0][j] = j;
  14. }
  15. for (i = 1; i <= b.length; i++) {
  16. for (j = 1; j <= a.length; j++) {
  17. if (b.charAt(i - 1) === a.charAt(j - 1)) {
  18. matrix[i][j] = matrix[i - 1][j - 1];
  19. }
  20. else {
  21. matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
  22. }
  23. }
  24. }
  25. return matrix[b.length][a.length];
  26. }