index.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. const array = [];
  3. const charCodeCache = [];
  4. const leven = (left, right) => {
  5. if (left === right) {
  6. return 0;
  7. }
  8. const swap = left;
  9. // Swapping the strings if `a` is longer than `b` so we know which one is the
  10. // shortest & which one is the longest
  11. if (left.length > right.length) {
  12. left = right;
  13. right = swap;
  14. }
  15. let leftLength = left.length;
  16. let rightLength = right.length;
  17. // Performing suffix trimming:
  18. // We can linearly drop suffix common to both strings since they
  19. // don't increase distance at all
  20. // Note: `~-` is the bitwise way to perform a `- 1` operation
  21. while (leftLength > 0 && (left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength))) {
  22. leftLength--;
  23. rightLength--;
  24. }
  25. // Performing prefix trimming
  26. // We can linearly drop prefix common to both strings since they
  27. // don't increase distance at all
  28. let start = 0;
  29. while (start < leftLength && (left.charCodeAt(start) === right.charCodeAt(start))) {
  30. start++;
  31. }
  32. leftLength -= start;
  33. rightLength -= start;
  34. if (leftLength === 0) {
  35. return rightLength;
  36. }
  37. let bCharCode;
  38. let result;
  39. let temp;
  40. let temp2;
  41. let i = 0;
  42. let j = 0;
  43. while (i < leftLength) {
  44. charCodeCache[i] = left.charCodeAt(start + i);
  45. array[i] = ++i;
  46. }
  47. while (j < rightLength) {
  48. bCharCode = right.charCodeAt(start + j);
  49. temp = j++;
  50. result = j;
  51. for (i = 0; i < leftLength; i++) {
  52. temp2 = bCharCode === charCodeCache[i] ? temp : temp + 1;
  53. temp = array[i];
  54. // eslint-disable-next-line no-multi-assign
  55. result = array[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2;
  56. }
  57. }
  58. return result;
  59. };
  60. module.exports = leven;
  61. // TODO: Remove this for the next major release
  62. module.exports.default = leven;