본문 바로가기
코테연습

4.Get the Middle Character

by hxunz 2022. 3. 11.

Description:

You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.

#Examples:

Kata.getMiddle("test") should return "es"

Kata.getMiddle("testing") should return "t"

Kata.getMiddle("middle") should return "dd"

Kata.getMiddle("A") should return "A"

#Input

A word (string) of length 0 < str < 1000 (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out.

#Output

The middle character(s) of the word represented as a string.

 

 

function getMiddle(s) {
  const odd = s.length % 2 === 1;
  const middleIndex = Math.floor(s.length / 2);

  if (odd) {
    return s[middleIndex]
  }
  return `${s[middleIndex - 1]}${s[middleIndex]}`;
}

이번에는 문제풀고 리팩토링까지 해봤다.

 

홀수를 2로 나누게 되면 소수점이 붙기 때문에 Math.floor() 함수를 사용했다.

Math.floor() 수는 주어진 숫자와 같거나 작은 정수 중에서 가장 큰 수를 반환합니다.

 

짝수일 경우에 가운데 숫자 2개를 리턴해야하는데 예를 들어서 'bb'가 리턴되어야하는데 'b' , 'b'로 리턴되는 상황이었다.

그래서 템플릿리터럴을 사용했다. 

Template Literals 템플릿 리터럴은 내장된 표현식을 허용하는 문자열 리터럴입니다. 여러 줄로 이뤄진 문자열과 문자 보간기능을 사용할 수 있습니다.

 

지금과 같은 간단한 코드에서는 삼항 연산자를 사용하는것도 좋은것같다.

조건부 삼항 연산자는 JavaScript에서 세 개의 피연산자를 취할 수 있는 유일한 연산자입니다. 맨 앞에 조건문 들어가고. 그 뒤로 물음표(?)와 조건이 truthy이라면 실행할 식이 물음표 뒤로 들어갑니다. 바로 뒤로 콜론(:)이 들어가며 조건이 거짓falsy이라면 실행할 식이 마지막에 들어갑니다. 보통 if 명령문의 단축 형태로 쓰입니다.

현재 위의 코드에 접목시켜본다면 

return odd ? s[middleIndex] : `${s[middleIndex - 1]}${s[middleIndex]}`;
이런식으로 사용할 수 있다.

 

'코테연습' 카테고리의 다른 글

6.Isograms  (0) 2022.03.16
5.You're a square!  (0) 2022.03.14
3.Descending Order  (0) 2022.03.10
2. Disemvowel Trolls  (0) 2022.03.09
1. Square Every Digit  (0) 2022.03.09

댓글