Optimizing code solution for Palindrome Index-Hackerrank I submitted my solution for palindrome Index coding challenge but I get "test cases terminated due to time out error". My code is working and so I don't know what else to do to optimize it. Please help:

function palindromeIndex(s) {
    let palindrome = s === s.split('').reverse().join('')
    if(!palindrome) {
        let i = 0
        let integerIndex = []
        let arr = s.split('')
        while(i &lt; s.length) {
            arr.splice(i,1)
            if(arr.join('') === arr.reverse().join('')) {
               integerIndex.push(i) 
            }
            arr = s.split('')
            i++
        }
        return integerIndex.length &gt; 0 ? integerIndex[0] : - 1
    }else {
        return -1
    }
}
It may well be an error @ Hackerrank. If I'm not mistaken the nodejs-code expects you to provide console input. Or you may have accidentally changed something in the surrounding code.

Concerning your code: writing ES20xx, it's good practice to terminate lines with a semicolon (;), because not doing so may result in nasty bugs. 


  let palindrome = s === s.split('').reverse().join('')


You don't need this variable. It could've been:

if(s !== s.split('').reverse().join('')) {

Furthermore, if you wanted to declare a variable, it could've been a const here (you are not modifying it afterwards).

Just for fun, here's an alternative approach, using substrings from the original given string:



"hannach,ava,reopaper,annana,ewve,blob,otto,michael,racecaar,wasitacatiwsaw"
  .split(",")
  .forEach(name =&gt; console.log(`[${name}] =&gt; ${palindromeIndex(name)}`));
  
function palindromeIndex(s) {
    if (`${[...s]}` === `${[...s].reverse()}`) { return "is palindrome"; }
    let i = 0;
    while(i &lt; s.length) {
      const sx = `${i &lt; 1 ? s.substr(1, 0) : s.substr(0, i)}${s.substr(i + 1)}`; 
      const  rsx = `${[...sx].reverse().join("")}`;
      if (sx === rsx) {
        return `removing '${s[i]}' (@ position ${i}): '${sx}'`;
      };
      i += 1;
    }
    return -1;
}
.as-console-wrapper { top: 0; max-height: 100% !important; }