find-suggestion.js 715 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.findSuggestion = findSuggestion;
  6. const {
  7. min
  8. } = Math;
  9. function levenshtein(a, b) {
  10. let t = [],
  11. u = [],
  12. i,
  13. j;
  14. const m = a.length,
  15. n = b.length;
  16. if (!m) {
  17. return n;
  18. }
  19. if (!n) {
  20. return m;
  21. }
  22. for (j = 0; j <= n; j++) {
  23. t[j] = j;
  24. }
  25. for (i = 1; i <= m; i++) {
  26. for (u = [i], j = 1; j <= n; j++) {
  27. u[j] = a[i - 1] === b[j - 1] ? t[j - 1] : min(t[j - 1], t[j], u[j - 1]) + 1;
  28. }
  29. t = u;
  30. }
  31. return u[n];
  32. }
  33. function findSuggestion(str, arr) {
  34. const distances = arr.map(el => levenshtein(el, str));
  35. return arr[distances.indexOf(min(...distances))];
  36. }