# Why doesn't my index start at 0?

Why doesn't my index start at 0?
0

#1

Can anyone tell me why indx in my reduce starts at 1 instead of 0?

Array.prototype.asString = function() {
return this.join('');
}

String.prototype.isPalindrome = function() {
return this == [...this].reverse().join('');
}

var longestPalindrome = function(s) {
[...s].reduce((acc, current, indx, arr) => {
var ans = acc;

for(let i=0; i < (arr.length - i ); i++){
let subStr = arr.asString().substr(indx , arr.length -i);
ans = (subStr.isPalindrome() && (subStr.length > (acc.length || 0))) ? subStr : ans ;
}

return ans;
}

),' ' };

#2

I believe you have the last two lines reversed:

} // this really should be closing the function

),' ' }; // I believe you meant for this line to be closing the reduce so it should have been },' ');

#3

thank you - I was staring at that for over an hour and didn’t see it.
Now I have it like this.

Array.prototype.asString = function() {
return this.join('');
}

String.prototype.isPalindrome = function() {
return String(this) === [...this].reverse().asString();
}

/**
* @param {string} s
* @return {string}
*/
function longestPalindrome(s) {
return [...s].reduce((acc, current, indx, arr) => {
var ans = acc;

for(let i=0; i < arr.length; i++){
let subStr = arr.asString().substr(indx , arr.length -i);
ans = (subStr.isPalindrome() && (subStr.length > ans.length)) ? subStr : ans ;
}
return ans;
}, '');
}

#4

Did you intend for the isPalindrome prototype function to return a true or false? You are not, but in your longestPalindrome function you are evaluating an expression which I would think you want a true or false value for isPalindrome. Because your current isPalindrome is going to return a string, when the expression below is evaluated, subStr.isPalindrome will always be true, because of coercion.

ans = (subStr.isPalindrome() && (subStr.length > (acc.length || 0)))

#5

Yes, doesn’t it? It’s comparing if the string is the same in reverse.

#6

seems to be working.

#7

@carl-parrish

You are correct. I read it wrong.

#8
String.prototype.isPalindrome = function() {
return this === [...this].reverse().asString();
}

#9

If I test your isPalindrome function like:

'eye'.isPalindrome();

I expect it to return true, but it returns false.

#10

yeah === doesn’t seem to work == does though.

#11

That is because this is an object containing a string and […this].reverse().asString() is a string. If you use String(this) === […this].reverse().asString() it will work correctly.