Comparing ascii scores of strings - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

ASCII Code

ASCII is a 7-bit character code where every single bit represents a unique character.

Every English alphabet has a unique decimal ascii code.

We are required to write a function that takes in two strings and calculates their ascii scores (i.e., the sum of ascii decimal of each character of string) and returns the difference.

Example

Let's write the code for this −

const str1 = 'This is the first string.';
const str2 = 'This here is the second string.';
const calculateScore = (str = '') => {
   return str.split("").reduce((acc, val) => {
      return acc + val.charCodeAt(0);
   }, 0);
};
const compareASCII = (str1, str2) => {
   const firstScore = calculateScore(str1);
   const secondScore = calculateScore(str2);
   return Math.abs(firstScore - secondScore);
};
console.log(compareASCII(str1, str2));

Output

Following is the output in the console −

536
raja
Published on 15-Sep-2020 08:55:05
Advertisements