DEV Community

loading...

Discussion on: How to Determine if a String is a Palindrome (in JavaScript)

nomoredeps profile image
NoMoreDeps • Edited

Not so sure either we can do shorter and faster :-)

function isPalindrome(string) {
  let left = 0;
  let right = string.length - 1;

  while (left <= right) {
    if (string[left] !== string[right]) return false;
    left++;
    right--;
  }

    return true;    
}

const isPalindrome2 =(str) => {
  const l = str.length;
  for(let i=0; i< (l / 2) >> 0; i++) {
    if (str[i] !== str[l-i-1]) return false;
  }
  return true;
}

console.time('isPalindrome');
for(var i = 0; i < 100000000; i++) {
    isPalindrome('asdfgfdsa')
}
console.timeEnd('isPalindrome')
console.time('isPalindrome2');
for(var i = 0; i < 100000000; i++) {
    isPalindrome2('asdfgfdsa')
}
console.timeEnd('isPalindrome2')    ;

VM254:26 isPalindrome: 3210.27978515625 ms
VM254:31 isPalindrome2: 2888.925048828125 ms
Enter fullscreen mode Exit fullscreen mode
Forem Open with the Forem app