index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. module.exports = {
  2. compareTwoStrings,
  3. findBestMatch
  4. };
  5. function compareTwoStrings(first, second) {
  6. first = first.replace(/\s+/g, '')
  7. second = second.replace(/\s+/g, '')
  8. if (!first.length && !second.length) return 1; // if both are empty strings
  9. if (!first.length || !second.length) return 0; // if only one is empty string
  10. if (first === second) return 1; // identical
  11. if (first.length === 1 && second.length === 1) return 0; // both are 1-letter strings
  12. if (first.length < 2 || second.length < 2) return 0; // if either is a 1-letter string
  13. let firstBigrams = new Map();
  14. for (let i = 0; i < first.length - 1; i++) {
  15. const bigram = first.substring(i, i + 2);
  16. const count = firstBigrams.has(bigram)
  17. ? firstBigrams.get(bigram) + 1
  18. : 1;
  19. firstBigrams.set(bigram, count);
  20. };
  21. let intersectionSize = 0;
  22. for (let i = 0; i < second.length - 1; i++) {
  23. const bigram = second.substring(i, i + 2);
  24. const count = firstBigrams.has(bigram)
  25. ? firstBigrams.get(bigram)
  26. : 0;
  27. if (count > 0) {
  28. firstBigrams.set(bigram, count - 1);
  29. intersectionSize++;
  30. }
  31. }
  32. return (2.0 * intersectionSize) / (first.length + second.length - 2);
  33. }
  34. function findBestMatch(mainString, targetStrings) {
  35. if (!areArgsValid(mainString, targetStrings)) throw new Error('Bad arguments: First argument should be a string, second should be an array of strings');
  36. const ratings = [];
  37. let bestMatchIndex = 0;
  38. for (let i = 0; i < targetStrings.length; i++) {
  39. const currentTargetString = targetStrings[i];
  40. const currentRating = compareTwoStrings(mainString, currentTargetString)
  41. ratings.push({target: currentTargetString, rating: currentRating})
  42. if (currentRating > ratings[bestMatchIndex].rating) {
  43. bestMatchIndex = i
  44. }
  45. }
  46. const bestMatch = ratings[bestMatchIndex]
  47. return { ratings, bestMatch, bestMatchIndex };
  48. }
  49. function areArgsValid(mainString, targetStrings) {
  50. if (typeof mainString !== 'string') return false;
  51. if (!Array.isArray(targetStrings)) return false;
  52. if (!targetStrings.length) return false;
  53. if (targetStrings.find(s => typeof s !== 'string')) return false;
  54. return true;
  55. }