본문 바로가기

1일1알고리즘

L2: Triple X, indexOf(), &&로 조건 설정 | Codewars [자바스크립트]

Codewars 7kyu 문제 L2: Triple X

 

Codewars: Achieve mastery through challenge

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

www.codewars.com

문자열이 주어짐. 문자열에서 가장 먼저 등장하는 소문자 "x"를 찾고 "xx"가 뒤따라 나오면 true, 아니면 false 찍어내는 문제. "xxx"가 존재하고 앞에 다른 "x"가 없는지 확인하는 문제라고 볼 수도.

 

function tripleX(str){
  let result = false;
  const index = str.indexOf("x");
  
  if (str[index + 1] === "x" && str[index + 2] === "x") {
    result = true;
  }
  
  return result;
}

문자열에 "x"가 없으면 false를 내보내야 하므로 기본 결과값을 false로 설정함.

indexOf()는 해당 문자가 처음으로 등장하는 인덱스를 알려줌.

"x"가 처음으로 나온 인덱스 바로 다음과 다다음이 모두 "x"면 true 찍어내라고 씀.

 

다른 답변들을 보는데 && 연산자로 조건식을 표현한 게 깔끔해 보임.

function tripleX(str){
  const index = str.indexOf("x");
  return index > -1 && index === str.indexOf("xxx")
}

 

&& 연산자는 왼쪽부터 falsey 값을 찾음. falsey 값이 나오면 해당 피연산자 값을 내보내고 끝까지 falsey 값이 없으면 마지막 값을 반환함.

위 코드에서 str에 "x"가 없으면 index 값은 -1일 것이므로 index > -1 값은 false. false 반환.

반면 str에 "x"가 있으면 index 값은 0 이상일 테고 index === str.indexOf("xxx") 값에 따라 함수 결과가 결정남.


Simple Fun #136: Missing Values, arr.reduce(), &&로 if 대체, find() filter() | Codewars [자바스크립트]

 

Simple Fun #136: Missing Values, arr.reduce(), &&로 if 대체, find() filter() | Codewars [자바스크립트]

Codewars 7kyu 문제 Simple Fun #136: Missing Values. Codewars: Achieve mastery through challenge Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and re..

fennecfox-dev.tistory.com