CodeBox CodeBox

JavaScript palindrome

Typescript / JS
けい

1. 🧐 Expected Output

reverse('apple') === 'leppa'
reverse('hello') === 'olleh'
reverse('Greetings!') === '!sgniteerG'


2.🤔 My Solution

2-1. First Solution

  • Turn str into an array with split' method
  • Use far loop and check if 'char' is equal to 'arr [lastIndex-index]'
function palindrome(str) {
  const arr = str.split('')
  const lastIndex = arr.length - 1
  let result = false

  for (let index = 0; index < arr.length; index++) {
    const char = arr[index]
    
    if (char !== arr[lastIndex - index]) {
      result = false
      break
    } else {
      result = true
    }
  }
  return result
}


2-2. Second Solution

function palindrome(str) {
  const arr = str.split('')
  const lastIndex = arr.length - 1

  for (let index = 0; index < arr.length; index++) {
    const char = arr[index]
    return char === arr[lastIndex - index]
  }
}


3.🎊 Best Solution

3-1. First possible solution

  • Turn str into an array with split method
  • Call reverse method
function palindrome(str) {
  const reversed = str.split('').reverse().join('')
  return str === reversed
}


3-2. Second possible solution

  • Call every method
function palindrome(str) {
  return str.split('').every((char, index) => {
    return char === str[str.length - index - 1]
  })
}

ABOUT ME

けい
ベンチャーのフロントエンジニア。 主にVueとTypescriptを使っています。ライターのための文字数カウントアプリ:https://easy-count.vercel.app/