```
var lengthOfLongestSubstringTwoDistinct = function(s) {
const chars = {};
let res = 0, count = 0, i = 0, j = -1;
while (j < s.length - 1) {
j++;
if (chars[s[j]] === undefined) {
if (count < 2) {
count++;
} else {
let other;
for (let c in chars) {
if (c !== s[i]) other = c;
}
if (chars[other] < chars[s[i]]) {
i = chars[other] + 1;
delete chars[other];
} else {
let temp = i;
i = chars[s[i]] + 1;
delete chars[s[temp]];
}
}
}
chars[s[j]] = j;
res = Math.max(res, j - i + 1);
}
return res;
};
```