test.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. var _a = require("./mod.js"), closest = _a.closest, distance = _a.distance;
  2. var levenshtein = function (a, b) {
  3. if (a.length === 0) {
  4. return b.length;
  5. }
  6. if (b.length === 0) {
  7. return a.length;
  8. }
  9. if (a.length > b.length) {
  10. var tmp = a;
  11. a = b;
  12. b = tmp;
  13. }
  14. var row = [];
  15. for (var i = 0; i <= a.length; i++) {
  16. row[i] = i;
  17. }
  18. for (var i = 1; i <= b.length; i++) {
  19. var prev = i;
  20. for (var j = 1; j <= a.length; j++) {
  21. var val = 0;
  22. if (b.charAt(i - 1) === a.charAt(j - 1)) {
  23. val = row[j - 1];
  24. }
  25. else {
  26. val = Math.min(row[j - 1] + 1, prev + 1, row[j] + 1);
  27. }
  28. row[j - 1] = prev;
  29. prev = val;
  30. }
  31. row[a.length] = prev;
  32. }
  33. return row[a.length];
  34. };
  35. var makeid = function (length) {
  36. var result = "";
  37. var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  38. var charactersLength = characters.length;
  39. for (var i = 0; i < length; i++) {
  40. result += characters.charAt(Math.floor(Math.random() * charactersLength));
  41. }
  42. return result;
  43. };
  44. for (var i = 0; i < 10000; i++) {
  45. var rnd_num1 = (Math.random() * 1000) | 0;
  46. var rnd_num2 = (Math.random() * 1000) | 0;
  47. var rnd_string1 = makeid(rnd_num1);
  48. var rnd_string2 = makeid(rnd_num2);
  49. var actual = distance(rnd_string1, rnd_string2);
  50. var expected = levenshtein(rnd_string1, rnd_string2);
  51. console.log(i);
  52. if (actual !== expected) {
  53. console.log("fail");
  54. }
  55. }