Counting rings in letters using JavaScript


Problem

We are required to write a JavaScript function that takes in a string of English alphabets.Our function should count the number of rings present in the string.

O', 'b', 'p', 'e', 'A', etc. all have one rings whereas 'B' has 2

Example

Following is the code −

 Live Demo

const str = 'some random text string';
function countRings(str){
   const rings = ['A', 'D', 'O', 'P', 'Q', 'R', 'a', 'b', 'd', 'e', 'g', 'o', 'p', 'q'];
   const twoRings = ['B'];
   let score = 0;
   str.split('').map(x => rings.includes(x)
   ? score++
   : twoRings.includes(x)
   ? score = score + 2
   : x
   );
   return score;
}
console.log(countRings(str));

Output

7

Updated on: 17-Apr-2021

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements