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;
}
),' ' };
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 },' ');
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;
}, '');
}
Yes, doesn’t it? It’s comparing if the string is the same in reverse.
String.prototype.isPalindrome = function() {
return this === [...this].reverse().asString();
}
yeah === doesn’t seem to work == does though.