test.ts 1.6 KB

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