Skip to content

Instantly share code, notes, and snippets.

@MeyCry
Last active December 12, 2019 18:03
Show Gist options
  • Save MeyCry/07de3714a0e34deb2028963a1bf0bd3a to your computer and use it in GitHub Desktop.
Save MeyCry/07de3714a0e34deb2028963a1bf0bd3a to your computer and use it in GitHub Desktop.
find longest substring in string
function find2(str) {
let _helper = [];
return str
.split('')
.reduce((acum, item, i, originalArr) => {
if (_helper.some(char => char === item)) {
acum.push(_helper);
_helper = [];
}
_helper.push(item);
if (i === originalArr.length - 1) {
acum.push(_helper);
}
return acum;
}, [])
.map(x => x.join(''))
.reduce(
(a, b) => (a.length > b.length ? a : b),
'',
);
}
console.log(find2('abcdcfepoi')); // cfepoi
console.log(find2('dertyuioplkjhgfdqwe')); // dertyuioplkjhgf
console.log(find2('')); // ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment