During an technical interview, I was asked to implement a basic palindrome function that excludes non-alphanumeric characters in Javascript (e.g. "A man, a plan, a canal, Panama."). The code that I came up with essentially looked like this:
function skipNonAlphanumeric(str,i,j) {
var regex = /[^a-zA-Z0-9]/;
if(regex.test(str[i])) {
i++;
return skipNonAlphanumeric(str,i,j);
};
if(regex.test(str[j])) {
j--;
return skipNonAlphanumeric(str,i,j);
};
return {i: i, j: j};
};
function isPalindrome(str) {
var j = str.length - 1;
var i = 0;
var indices, ci, cj;
while(i < j) {
indices = skipNonAlphanumeric(str,i,j);
i = indices.i;
j = indices.j;
ci = str[i].toLowerCase();
cj = str[j].toLowerCase();
if(ci !== cj) {
return false;
};
j--;
i++;
};
return true;
};
My interviewer than proceeded to tell me that:
use of regex is overkill and prone to error.
I accepted this statement during the interview, but upon researching it afterwards, I haven't been able to find a good alternative. This answer to a different question suggests that using charCodeAt()
is more performant, but I can't imagine that I would be expected to know the necessary character codes to implement a solution like that.
I'm aware that my code isn't necessarily the best solution to the problem, but does anyone have any ideas as to what my interviewer could have been looking for instead?