ASCII sum difference of strings in 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.

Let’s write the code for this function −

Example

The code for this will be −

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

Output

The output in the console −

116
raja
Updated on 15-Oct-2020 08:53:55

Advertisements