countVowelConsonants

with Carmen Salas • 2024/11/12

Solution

/*
**Problem**
Get the 'value sum' of a string containing lowercase alphabet characters.
A character's value is determined like below:
  - vowels are 1
  - consonants are 2

**Examples/Edge Cases:** 
'abcde' => 1 + 2 + 2 + 2 + 1 => 8
'' => 0

**Data Structures**
- String
- Loops

**Algorithm** 
For each character in the string:
  - if vowel, sum + 1
  - if consonant, sum + 2
*/

function solution(s) {
  // hom and regex
  return [...s].reduce((sum, curr) => (/[aeiou]/.test(curr)) ? sum+1 : sum+2 , 0);
  
  // looping and checking with sets
  // (with a small pool like this, array should be just fine too)
  let sum = 0;
  const vowels = new Set(['a', 'e', 'i', 'o', 'u']);
  for (const char of s) {
    if (vowels.has(char)) {
      sum += 1;
    } else {
      sum += 2;
    }
  }
  return sum;
}

Last updated