-1

Task: https://www.codewars.com/kata/54bb6f887e5a80180900046b/train/javascript

My solution:

function longestPalindrome(str){

var Palindromes = [], reverser = i => i.split("").reverse().join(""), l = str.length;
  
  if (str === Infinity || str === -Infinity)  {return 0} 

else{
for (let i = l ; i >= 0; i--){
  
 for(let j = 0; j < l; j++){
   temp = str.slice(j, i)
 if (reverser(temp) === temp){
   Palindromes.push(temp)
   }
  } 
 } 
  
 return Math.max(...Palindromes.map(e => e.length));
}
}

My code works perfectly in my editor console, but when I submit it on codewars it says "-Infinity should return 0"? -Infinity returns 0 in other consoles however? Is there something wrong with my code? Please don't link to another question. I think my code works (?) except for a minor tweak somewhere.

  • 2
    I'm not sure why you even want to check if input is `Infinity`? Your task doesn't mention handling any types but string at all. – Oleg V. Volkov Dec 07 '21 at 13:06
  • I was thinking the same, but when I don't specify for Infinity as an input it returns "Infinity should return 0", so I added that initial "if" block. – untitiledunmastered Dec 07 '21 at 13:09
  • 1
    I suppoe that codewars expect you to return 0 if the input is not a string `if (typeof str !== "string") {return 0}` – jonatjano Dec 07 '21 at 13:10
  • 1
    How is your string supposed to `===` the number `Infinity`? – DustInComp Dec 07 '21 at 13:10
  • 2
    Does this answer your question? [Longest Palindrome](https://stackoverflow.com/questions/70170066/longest-palindrome) – Liam Dec 07 '21 at 13:11

1 Answers1

0

Check this out. Kind of brute-force solution

str = 'I like racecars that go fast'
const longestPalindrome = (s) => {
  const strLength = s.length
  if (strLength <= 1) return strLength;


  const strReverse = (s) => [...s].reverse().join('');

  colls = [...Array(strLength)].map((c, i) => i);
  rows = [...Array(strLength)].map((c, i) => i);

  const indexes = rows.reduce((acc, r) => (
    [...acc, ...colls.map((c) => (r > c) ? [c, r] : false)]
  ), []).filter((o) => o);

  const results = indexes.map(([begin, end]) => {
    const chunk = s.slice(begin, end + 1);
    return (strReverse(chunk) === chunk) ? end - begin + 1 : 0;
  });

  return Math.max(...results) || 1;
};
console.log(longestPalindrome(str))
A1exandr Belan
  • 4,442
  • 3
  • 26
  • 48