Hyebin‘s blog
article thumbnail
Published 2022. 1. 18. 18:29
[Codewars/JS] Vowel Count Algorithm/Codewars

Detail

Return the number (count) of vowels in the given string.

We will consider a, e, i, o, u as vowels for this Kata (but not y).

The input string will only consist of lower case letters and/or spaces.

 

 

<code>

function getCount(str) {
  var vowelsCount = 0;
  str = str
    .split("")
    .filter(
      (a) =>
        a.match("a") ||
        a.match("e") ||
        a.match("i") ||
        a.match("o") ||
        a.match("u")
    );
  vowelsCount = str.length;
  return vowelsCount;
}

/*

문자열이 주어졌을 때, 
a, e, i, o, u을 포함하는 수를 구하기

*/

 

특정 문자열이 주어졌을 때 그 문자열이 들어있는지 검사하기위해

일단 fillter 함수를 사용했다. fillter 함수는 Javascript의 array가 가진 함수로

일단 문자열을 split로 배열로 잘라준 다음 필터함수로 문자열을 하나씩 검사하면서 match함수로 포함되어 있는 값만 골랐다. 그리고 그 값의 길이를 반환해줬다.

 

<other code>

function getCount(str) {
  return (str.match(/[aeiou]/ig)||[]).length;
}

정규식을 이용하여 깔끔하고 간단하게 리턴값을 구했다.

 

function getCount(str) {
  var vowelsCount = 0;
  var vowels = ["a","e","i","o","u"];
  for(var i = 0;i < str.length;i++){
    for(var j=0;j<vowels.length;j++){
      if(str[i] === vowels[j]){
        vowelsCount++;
      }
    }
  }
  
  return vowelsCount;
}

for문을 두번 돌면서 str의 값과 vowels에 저장된 값이 같으면 count를 증가시켜줬다.

직관적이면서 함수 사용을 최소화한 깔끔한 방법이다.

 

function getCount(str) {
 return str.split('').filter(c => "aeiouAEIOU".includes(c)).length;
}

내가 사용한 방법이랑 비슷하지만 includes()함수를 사용하였다.

includes() 함수는 배열이 특정값을 포함하고 있는지의 여부를 boolean 값으로 반환한다.

처음에 includes함수를 사용하려고 시도했다가 값이  boolean 값으로 반환한다는 생각에 바로 포기했었다.

하지만 위 코드와 같이 찾고자하는 값을 앞에 넣어주고, filter 함수를 실행했을 때, true의 값만 출력해준다!!

 

원하는 값이 잘 뽑아져 나왔다! 

 

 

위 코드를 보고 이 와 같이 수정을 해보았다.

function getCount(str) {
  var vowelsCount = 0;
  str = str.split("").filter((a) => "a, e, i, o, u".match(a));
  console.log(str);
  return vowelsCount;
}

잘 동작한다. 하나의 기술을 얻은 기분이라 기쁘다 !

'Algorithm > Codewars' 카테고리의 다른 글

[Codewars/JS] Disemvowel Trolls  (0) 2022.01.21
[Codewars/JS] Find the odd int  (0) 2022.01.20
[Codewars/JS] Moving Zeros To The End  (0) 2022.01.14
[Codewars/JS] RGB To Hex Conversion  (0) 2022.01.13
[Codewars/JS] Two to One  (0) 2022.01.13
profile

Hyebin‘s blog

@hyebin Lee

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그