Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Last active October 25, 2022 20:52
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 sebinsua/d5cdcf0ad9f8a8bd6dff5f0e75678096 to your computer and use it in GitHub Desktop.
Save sebinsua/d5cdcf0ad9f8a8bd6dff5f0e75678096 to your computer and use it in GitHub Desktop.
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