Skip to content

Instantly share code, notes, and snippets.

@katai5plate
Forked from kurone-kito/groupByPrefix.ts
Last active June 19, 2019 01:56
Show Gist options
  • Save katai5plate/d180289cae48d0295e68abff133c4ea5 to your computer and use it in GitHub Desktop.
Save katai5plate/d180289cae48d0295e68abff133c4ea5 to your computer and use it in GitHub Desktop.
Group duplicate prefixes in the strings: (src: string[]) => string[]
const getInitials = (src, length) => {
if (length === void 0) { length = 1; }
return Array.from(new Set(src.map(v => v.substring(0, length))));
};
export default src => getInitials(src).map(initial => {
const list = src.filter(v => v.match(`^${initial}`));
const rec = (prev, length) => {
if (length === void 0) { length = 2; }
const _a = getInitials(list, length);
const word = _a[0];
const l = _a.slice(1).length;
return l || list[0].length < length ? prev : rec(word, length + 1);
};
return rec(initial);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment