Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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