areYouPlaying.js (8kyu 43)

Codewars 알고리즘 풀이


Problem

  • If your name starts with the letter R or lower case r, you are playing banjo.
    • 이름이 R 또는 r로 시작한다면, name + ‘plays banjo’를 반환한다.
    • 그렇지 않으면, name + ‘does not play banjo’를 반환한다.


Solution 01

function areYouPlaying(name) {
  if (name[0] === 'R' || name[0] === 'r') {
    return name + ' plays banjo';
  } else {
    return name + ' does not play banjo';
  }
}

areYouPlaying('Sam');    // Sam does not play banjo
areYouPlaying('Ralph');  // Ralph plays banjo


Solution 02

function areYouPlaying(name) {
  if (name[0] === 'R' || name[0] === 'r') {
    return `${name} plays banjo`;
  } else {
    return `${name} does not play banjo`;
  }
}

areYouPlaying('Sam');    // Sam does not play banjo
areYouPlaying('Ralph');  // Ralph plays banjo


Solution 03

function areYouPlaying(name) {
  if (name[0].toLowerCase() === 'r') {
    return `${name} plays banjo`;
  } else {
    return `${name} does not play banjo`;
  }
}

areYouPlaying('Sam');    // Sam does not play banjo
areYouPlaying('Ralph');  // Ralph plays banjo

toLowerCase() 메소드

문자열을 소문자로 변환한다.


Solution 04

function areYouPlaying(name) {
  return `${name} ${name[0].toLowerCase() === 'r' ? 'plays' : 'does not play'} banjo`;
}

areYouPlaying('Sam');    // Sam does not play banjo
areYouPlaying('Ralph');  // Ralph plays banjo


Solution 05

function areYouPlaying(name) {
  return `${name} ${/^r/i.test(name) ? 'plays' : 'does not play'} banjo`;
}

areYouPlaying('Sam');    // Sam does not play banjo
areYouPlaying('Ralph');  // Ralph plays banjo

정규표현식 (RegExp)

^: 입력의 시작 부분에 대응

i: 대소문자 구분 없는 검색

test(): 대응되는 문자열이 있는지 검색하고, true/false를 반환한다.