Skip to content

Instantly share code, notes, and snippets.

@redrambles
Last active August 16, 2021 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redrambles/e28832afb3cbbf84174cb65bdf092bce to your computer and use it in GitHub Desktop.
Save redrambles/e28832afb3cbbf84174cb65bdf092bce to your computer and use it in GitHub Desktop.
/***
Given a string X, will return true if palindrome and false if not
Return value: bool
***/
const isPalindrome = (string) => {
return string === string.split("").reverse().join("")
}
/***
Given a string X, will return longest substring that is a palindrome, if it exists.
Return value: string
***/
const pSubstring = (string) => {
// Is this thing already a palindrome? Then return it and call it a day.
if (isPalindrome(string)){
return string
}
// Ok, it's not, so let's dig.
const possibilities = []
for (let l = string.length - 1; l > 0; l--){
string = string.slice(0, l);
for (let i = 0; i < string.length; i++){
let subString = string.slice(i);
if (subString.length > 2 && isPalindrome(subString)){
possibilities.push(subString)
}
}
}
// No matches? bail
if (possibilities.length === 0){
return "You got nothing";
}
// Return longest match
return possibilities.reduce((acc, string) => acc.length < string.length ? string : acc, possibilities[0]);
}
pSubstring("hellobablo") // "bab"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment