Created
January 16, 2019 17:15
-
-
Save bessfernandez/f1464465ae79ba0c23d70c21baded21a to your computer and use it in GitHub Desktop.
This file contains 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
// Just a fun experiment at testing palindromes by division | |
// test if a string is a palindrome by dividing length of string and looking at left and right | |
function isPalindromeByDivision(str) { | |
if (!str) { | |
return; | |
} | |
let result; | |
// clean up string - remove spaces and enforce casing | |
let cleanedString = str.replace(/\s/g, '').toLowerCase(); | |
// find middle | |
// Note: that by using floor we will get the min of whole length | |
// so if there are odd amount of characters the very middle character will not be read | |
// which is correct in cases like `alula` we want to ignore the `u` | |
var middle = Math.floor(cleanedString.length / 2); | |
// store left hand side of string up to middle | |
let leftStr = cleanedString.slice(0, middle) | |
// get right hand side of string and reverse, then join back to string | |
let rightStrReversed = cleanedString.slice('-' + middle).split('').reverse().join(''); | |
// is a palindrome if left and right string are the same | |
return leftStr === rightStrReversed; | |
} | |
let phrase = 'A nut for a jar of tuna'; | |
let isPalindrome = isPalindromeByDivision(phrase) | |
console.log(`${phrase} is a palindrome: ${isPalindrome}`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment