Last active
April 25, 2026 20:55
-
-
Save kauefraga/2a167a0cddec1a81692b3b0f4c7207d7 to your computer and use it in GitHub Desktop.
Discover if a word is a palindrome, using JavaScript built-in array methods, manually reversing the string array or moving two pointers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // $ bun init | |
| // $ bun run is-palindrome.ts | |
| function isPalindrome(word: string) { | |
| return word === word.split('').reverse().join(''); | |
| } | |
| console.log('[v1] Array<string>.reverse'); | |
| console.log('renner', isPalindrome('renner')); | |
| console.log('cachorro', isPalindrome('cachorro')); | |
| console.log('kaiak', isPalindrome('kaiak')); | |
| // ------ | |
| function reverseLetters(letters: string[]) { | |
| let reversedLetters: string[] = []; | |
| for (let i = 0; i < letters.length; i++) { | |
| reversedLetters[i] = letters[letters.length - 1 - i] as string; | |
| } | |
| return reversedLetters; | |
| } | |
| function isPalindromeV2(word: string) { | |
| return word === reverseLetters(word.split('')).join(''); | |
| } | |
| console.log('[v2] Manually reverse array'); | |
| console.log('renner', isPalindromeV2('renner')); | |
| console.log('cachorro', isPalindromeV2('cachorro')); | |
| console.log('kaiak', isPalindromeV2('kaiak')); | |
| // ------ | |
| function isPalindromeV3(word: string) { | |
| let left = 0; | |
| let right = word.length - 1; | |
| while (left < right) { | |
| if (word[left] !== word[right]) { | |
| return false; | |
| } | |
| left++; | |
| right--; | |
| } | |
| return true; | |
| } | |
| console.log('[v3] two pointers'); | |
| console.log('renner', isPalindromeV3('renner')); | |
| console.log('cachorro', isPalindromeV3('cachorro')); | |
| console.log('kaiak', isPalindromeV3('kaiak')); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment