Compare Strings in JavaScript and return percentage of likeliness

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that can compare two strings and return the percentage likeliness of how much they are alike. The percentage will be nothing but a measure of many characters the two strings have in common.

If they are completely similar the output should be 100, and if they contain no common character at all, the output should be 0.

Example

const calculateSimilarity = (str1 = '', str2 = '') => {
   let longer = str1;
   let shorter = str2;
   if (str1.length < str2.length) {
      longer = str2; shorter = str1;
   }
   let longerLength = longer.length;
   if (longerLength == 0) {
      return 1.0;
   }
return +((longerLength - matchDestructively(longer, shorter)) / parseFloat(longerLength) * 100).toFixed(2);
};
const matchDestructively = (str1 = '', str2 = '') => {
   str1 = str1.toLowerCase();
   str2 = str2.toLowerCase();
   let arr = new Array();
   for (let i = 0; i <= str1.length; i++) {
      let lastValue = i;
      for (let j = 0; j <= str2.length; j++) {
         if (i == 0){
            arr[j] = j;
         }else if(j > 0){
            let newValue = arr[j - 1];
            if(str1.charAt(i - 1) != str2.charAt(j - 1))
            newValue = Math.min(Math.min(newValue, lastValue), arr[j]) + 1;
            arr[j - 1] = lastValue; lastValue = newValue;
         }
      }
      if (i > 0) arr[str2.length] = lastValue;
   }
   return arr[str2.length];
};
console.log(calculateSimilarity('Mathematics','Mathamatecs'));

Output

This will produce the following output −

[
   [ 1, 10, 100 ], [ 1, 10, 200 ],
   [ 1, 10, 300 ], [ 1, 20, 100 ],
   [ 1, 20, 200 ], [ 1, 20, 300 ],
   [ 2, 10, 100 ], [ 2, 10, 200 ],
   [ 2, 10, 300 ], [ 2, 20, 100 ],
   [ 2, 20, 200 ], [ 2, 20, 300 ]
]
raja
Published on 25-Nov-2020 05:11:40
Advertisements