π 1. λ¬Έμ
[Codewars, 7kyu] Get the Middle Character
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.
Kata.getMiddle("test") should return "es"
Kata.getMiddle("testing") should return "t"
Kata.getMiddle("middle") should return "dd"
Kata.getMiddle("A") should return "A"
β νμ΄
function getMiddle(s) {
const str = s.split("");
const count = str.length;
if (count % 2) {
return str[Math.floor(count / 2)];
} else {
return str[count / 2 - 1] + str[count / 2];
}
}
π Best
function getMiddle(s) {
return s.substr(Math.ceil(s.length / 2 - 1), s.length % 2 === 0 ? 2 : 1);
}
- κ°μ΄λ° λ¬Έμμ΄ μ°ΎκΈ° λ¬Έμ λ‘, bestνμ΄μμ μ¬μ©ν
substr()
λ©μλλ λ¬Έμμ΄μμ νΉμ μμΉμμ μμνμ¬ νΉμ λ¬Έμ μ λ§νΌμ λ¬Έμλ€μ λ°ννλ λ©μλλ€. κ·Έλ°λ° MDNλ¬Έμμμ ν΄λΉ λ©μλλ μ¬μ©νμ§ λ§ κ²μ κΆμ₯νλ λΆλ‘μ΄ μμ΄μsubstr()
λ μμ°λ 걸루.. μΌνμ°μ°μλ μ¬μ©ν΄μ μ½λ κ°κ²°νκ² λ§λ€κΈ°