Untitled
3 years ago in Plain Text
var TEST = function () {
/**
* i = index
* ┌ len=1 => (i , i ) ┐ // origin, odd
* └ len=2 => (i , i+1) ┘ // go forward, even
* ┌ len=3 => (i-1, i+1) ┐ // go backward, odd
* └ len=4 => (i-1, i+2) ┘ // go forward, even
* ┌ len=5 => (i-2, i+2) ┐ // go backward, odd
* └ len=6 => (i-2, i+3) ┘ // go forward, even
*/
let _strLen = 0;
const _getMatchLen = (str, si, ei) => {
while (si >= 0 && ei < _strLen && str[si] === str[ei]) {
si--;
ei++;
}
return ei - si - 1; // (ei-1) - (si+1) + 1;
}
return {
exec: function (str) {
if (!str) { return ''; }
_strLen = str.length;
let start = NaN;
let len = 0;
for (let i = 0; i < _strLen; ++i) {
if (!str[Math.ceil(len / 2)]) {
break;
}
let matchLen = Math.max(_getMatchLen(str, i, i), _getMatchLen(str, i, i + 1));
if (matchLen > len) {
len = matchLen;
start = i - Math.ceil(matchLen / 2) + 1;
}
}
return str.substr(start, len);
}
};
}();