#559 Improve Palindrome check

* #559

* #559

* #559

* #559

Co-authored-by: LOkesh <lpatil@rewardhealth.com>
This commit is contained in:
Lokesh Patil
2021-02-17 01:48:00 +05:30
committed by GitHub
parent 21b003ec70
commit 4bc2b28b7e

View File

@ -5,20 +5,13 @@ const checkPalindrome = (str) => {
if (typeof str !== 'string') { if (typeof str !== 'string') {
return 'Not a string' return 'Not a string'
} }
// Store the length of the input string in a variable if (str.length === 0) {
const length = str.length
if (length === 0) {
return 'Empty string' return 'Empty string'
} }
// Iterate through the length of the string // Reverse only works with array, thus conevert the string to array, reverse it and convert back to string
// Compare the first character to the last, the second character to the second last, and so on // return as palindrome if the reversed string is equal to the input string
for (let i = 0; i < length / 2; i++) { const reversed = [...str].reverse().join('')
// at the first instance of a mismatch return str === reversed ? 'Palindrome' : 'Not a Palindrome'
if (str[i] !== str[length - 1 - i]) {
return 'Not a Palindrome'
}
}
return 'Palindrome'
} }
export { checkPalindrome } export { checkPalindrome }