const solution = (s, t) =>
s.split('').map((char, index) => {
const leftIndex =
s.lastIndexOf(t, index) == -1
? Number.MAX_SAFE_INTEGER
: Math.abs(s.lastIndexOf(t, index) - index);
const rightIndex =
s.indexOf(t, index) == -1
? Number.MAX_SAFE_INTEGER
: s.indexOf(t, index) - index;
return Math.min(leftIndex, rightIndex);
});
const result = solution('teachermode', 'e');
console.log(result);
const solution = (s, t) => {
let standard = s.length;
return (
s
.split('')
.map((char, index) => {
if (index == s.length - 1) standard = s.length;
return char == t
? { char, distance: (standard = 0) }
: { char, distance: ++standard };
})
.reverse()
.map(({ char, distance }) =>
char == t
? Math.min(distance, (standard = 0))
: Math.min(distance, ++standard),
)
.reverse()
);
};
const result = solution('teachermode', 'e');
console.log(result);