Created
June 28, 2023 00:51
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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