You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
1.9 KiB

4 years ago
  1. 'use strict';
  2. module.exports = (function()
  3. {
  4. function _min(d0, d1, d2, bx, ay)
  5. {
  6. return d0 < d1 || d2 < d1
  7. ? d0 > d2
  8. ? d2 + 1
  9. : d0 + 1
  10. : bx === ay
  11. ? d1
  12. : d1 + 1;
  13. }
  14. return function(a, b)
  15. {
  16. if (a === b) {
  17. return 0;
  18. }
  19. if (a.length > b.length) {
  20. var tmp = a;
  21. a = b;
  22. b = tmp;
  23. }
  24. var la = a.length;
  25. var lb = b.length;
  26. while (la > 0 && (a.charCodeAt(la - 1) === b.charCodeAt(lb - 1))) {
  27. la--;
  28. lb--;
  29. }
  30. var offset = 0;
  31. while (offset < la && (a.charCodeAt(offset) === b.charCodeAt(offset))) {
  32. offset++;
  33. }
  34. la -= offset;
  35. lb -= offset;
  36. if (la === 0 || lb < 3) {
  37. return lb;
  38. }
  39. var x = 0;
  40. var y;
  41. var d0;
  42. var d1;
  43. var d2;
  44. var d3;
  45. var dd;
  46. var dy;
  47. var ay;
  48. var bx0;
  49. var bx1;
  50. var bx2;
  51. var bx3;
  52. var vector = [];
  53. for (y = 0; y < la; y++) {
  54. vector.push(y + 1);
  55. vector.push(a.charCodeAt(offset + y));
  56. }
  57. var len = vector.length - 1;
  58. for (; x < lb - 3;) {
  59. bx0 = b.charCodeAt(offset + (d0 = x));
  60. bx1 = b.charCodeAt(offset + (d1 = x + 1));
  61. bx2 = b.charCodeAt(offset + (d2 = x + 2));
  62. bx3 = b.charCodeAt(offset + (d3 = x + 3));
  63. dd = (x += 4);
  64. for (y = 0; y < len; y += 2) {
  65. dy = vector[y];
  66. ay = vector[y + 1];
  67. d0 = _min(dy, d0, d1, bx0, ay);
  68. d1 = _min(d0, d1, d2, bx1, ay);
  69. d2 = _min(d1, d2, d3, bx2, ay);
  70. dd = _min(d2, d3, dd, bx3, ay);
  71. vector[y] = dd;
  72. d3 = d2;
  73. d2 = d1;
  74. d1 = d0;
  75. d0 = dy;
  76. }
  77. }
  78. for (; x < lb;) {
  79. bx0 = b.charCodeAt(offset + (d0 = x));
  80. dd = ++x;
  81. for (y = 0; y < len; y += 2) {
  82. dy = vector[y];
  83. vector[y] = dd = _min(dy, d0, dd, bx0, vector[y + 1]);
  84. d0 = dy;
  85. }
  86. }
  87. return dd;
  88. };
  89. })();