Last active
October 25, 2022 20:52
-
-
Save sebinsua/d5cdcf0ad9f8a8bd6dff5f0e75678096 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
function* getOddPalindromesOutwardsFromCentre(str, index) { | |
let left = index - 1; | |
let right = index + 1; | |
let current = str[index]; | |
yield current; | |
while (left >= 0 && right < str.length && str[left] === str[right]) { | |
current = `${str[left]}${current}${str[right]}`; | |
yield current; | |
left--; | |
right++; | |
} | |
} | |
function* getEvenPalindromesOutwardsFromCentre(str, index) { | |
let left = index; | |
let right = index + 1; | |
let current = ""; | |
while (left >= 0 && right < str.length && str[left] === str[right]) { | |
current = `${str[left]}${current}${str[right]}`; | |
yield current; | |
left--; | |
right++; | |
} | |
} | |
function* getPalindromes(str) { | |
for (let index = 0; index < str.length; index++) { | |
yield* getOddPalindromesOutwardsFromCentre(str, index); | |
yield* getEvenPalindromesOutwardsFromCentre(str, index); | |
} | |
} | |
const palindromes = Array.from(getPalindromes("aaa")); | |
console.log(palindromes); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment