palindrome

Problem

์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์„ ๋’ค์ง‘์—ˆ์„ ๋•Œ ๋˜‘๊ฐ™์€ ๋‹จ์–ด๋ฉด true, ์•„๋‹ˆ๋ฉด false๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

Solution

  1. reverse() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ

function palindrome(str) {
   let reversed = str.split('').reverse().join('');

    return str === reversed;
}
  1. every() ๋ฉ”์„œ๋“œ ์‚ฌ์šฉํ•˜๊ธฐ

function palindrome(str) {
    return str.split('').every((char, index) => char === str[str.length - index - 1]);
}
  1. reduce() ๋ฉ”์„œ๋“œ ์‚ฌ์šฉํ•˜๊ธฐ

function palindrome(str) {
  let reversed =  str.split('').reduce((reversed, char) => char + reversed, '');

    return str === reversed;
}

Discussion

every() ๋ฉ”์„œ๋“œ ์‚ฌ์šฉํ•˜๊ธฐ

every() ๋ฉ”์„œ๋“œ๋Š” ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์š”์†Œ๊ฐ€ ์ฃผ์–ด์ง„ ํ•จ์ˆ˜๋กœ ๊ตฌํ˜„๋œ ํ…Œ์ŠคํŠธ๋ฅผ ํ†ต๊ณผํ•˜๋Š”์ง€ ํ…Œ์ŠคํŠธํ•œ๋‹ค. ์ฃผ์–ด์ง„ ํ•จ์ˆ˜๊ฐ€ ๋ฐฐ์—ด ์š”์†Œ๋งˆ๋‹ค ํ•œ ๋ฒˆ์”ฉ ํ˜ธ์ถœ๋˜์–ด true๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด true๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ๋ฌธ์ž์—ด์„ ๋ฐฐ์—ด๋กœ ๋งŒ๋“ค์–ด ๋ฐฐ์—ด์˜ ๊ฐ ์š”์†Œ์™€ ๋’ค์ง‘์€ ๋ฌธ์ž์—ด์˜ ๊ฐ ์š”์†Œ๋ฅผ ๋น„๊ตํ•œ๋‹ค. ๋ชจ๋“  ์š”์†Œ๊ฐ€ ๊ฐ™๋‹ค๋ฉด true๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

Last updated