test.js 1.6 KB

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