levenshtein.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var makeString = require('./helper/makeString');
  2. /**
  3. * Based on the implementation here: https://github.com/hiddentao/fast-levenshtein
  4. */
  5. module.exports = function levenshtein(str1, str2) {
  6. 'use strict';
  7. str1 = makeString(str1);
  8. str2 = makeString(str2);
  9. // Short cut cases
  10. if (str1 === str2) return 0;
  11. if (!str1 || !str2) return Math.max(str1.length, str2.length);
  12. // two rows
  13. var prevRow = new Array(str2.length + 1);
  14. // initialise previous row
  15. for (var i = 0; i < prevRow.length; ++i) {
  16. prevRow[i] = i;
  17. }
  18. // calculate current row distance from previous row
  19. for (i = 0; i < str1.length; ++i) {
  20. var nextCol = i + 1;
  21. for (var j = 0; j < str2.length; ++j) {
  22. var curCol = nextCol;
  23. // substution
  24. nextCol = prevRow[j] + ( (str1.charAt(i) === str2.charAt(j)) ? 0 : 1 );
  25. // insertion
  26. var tmp = curCol + 1;
  27. if (nextCol > tmp) {
  28. nextCol = tmp;
  29. }
  30. // deletion
  31. tmp = prevRow[j + 1] + 1;
  32. if (nextCol > tmp) {
  33. nextCol = tmp;
  34. }
  35. // copy current col value into previous (in preparation for next iteration)
  36. prevRow[j] = curCol;
  37. }
  38. // copy last col value into previous (in preparation for next iteration)
  39. prevRow[j] = nextCol;
  40. }
  41. return nextCol;
  42. };