Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save VictorQueiroz/4eff3fc8e3395c897a42641a83ef52eb to your computer and use it in GitHub Desktop.
Save VictorQueiroz/4eff3fc8e3395c897a42641a83ef52eb to your computer and use it in GitHub Desktop.
Get abbreviation from the string by comparing start of the string. Useful for creating convenient TypeScript enum names.
const s = [
"ApiAuthTypeFacebook",
"ApiAuthTypeGoogle",
"ApiAuthTypeLinkedIn",
"ApiAuthTypeGithub",
];
function getAbbreviationFromStartSimilarity(s: string[]) {
let match = "";
for (const n of s) {
for (const n2 of s) {
for (let i = 0; i < n.length; i++) {
const slice = n.substring(0, n.length - 1 - i);
if (n2.startsWith(slice) && s.every((n) => n.startsWith(slice)) && slice.length > match.length) {
match = slice;
}
}
}
}
return s.map((l) => l.substring(match.length));
}
/**
* output of the call below is:
* ['Facebook', 'Google', 'LinkedIn', 'Github']
*/
console.log(getAbbreviationFromStartSimilarity(s));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment