index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* eslint-disable no-nested-ternary */
  2. 'use strict';
  3. var arr = [];
  4. var charCodeCache = [];
  5. module.exports = function (a, b) {
  6. if (a === b) {
  7. return 0;
  8. }
  9. var swap = a;
  10. // Swapping the strings if `a` is longer than `b` so we know which one is the
  11. // shortest & which one is the longest
  12. if (a.length > b.length) {
  13. a = b;
  14. b = swap;
  15. }
  16. var aLen = a.length;
  17. var bLen = b.length;
  18. if (aLen === 0) {
  19. return bLen;
  20. }
  21. if (bLen === 0) {
  22. return aLen;
  23. }
  24. // Performing suffix trimming:
  25. // We can linearly drop suffix common to both strings since they
  26. // don't increase distance at all
  27. // Note: `~-` is the bitwise way to perform a `- 1` operation
  28. while (aLen > 0 && (a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen))) {
  29. aLen--;
  30. bLen--;
  31. }
  32. if (aLen === 0) {
  33. return bLen;
  34. }
  35. // Performing prefix trimming
  36. // We can linearly drop prefix common to both strings since they
  37. // don't increase distance at all
  38. var start = 0;
  39. while (start < aLen && (a.charCodeAt(start) === b.charCodeAt(start))) {
  40. start++;
  41. }
  42. aLen -= start;
  43. bLen -= start;
  44. if (aLen === 0) {
  45. return bLen;
  46. }
  47. var bCharCode;
  48. var ret;
  49. var tmp;
  50. var tmp2;
  51. var i = 0;
  52. var j = 0;
  53. while (i < aLen) {
  54. charCodeCache[start + i] = a.charCodeAt(start + i);
  55. arr[i] = ++i;
  56. }
  57. while (j < bLen) {
  58. bCharCode = b.charCodeAt(start + j);
  59. tmp = j++;
  60. ret = j;
  61. for (i = 0; i < aLen; i++) {
  62. tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1;
  63. tmp = arr[i];
  64. ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2;
  65. }
  66. }
  67. return ret;
  68. };