Last active
June 12, 2021 15:23
-
-
Save jomifepe/cfd52b52e887e03e815b43afec37deb2 to your computer and use it in GitHub Desktop.
Simple function that looks for unique words prefixed by something and prints them sorted as a TypeScript union
This file contains hidden or 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
/** | |
* Simple function that looks for unique words prefixed by something and prints them sorted as a TypeScript union | |
* Usage: getPrefixedNamesAsUnion(`.icon-alert{color: white}.icon-arrow{color: red}`, '.icon-'); | |
* Output: 'alert' | 'arrow' | |
*/ | |
getPrefixedStringsAsUnion = (str, prefix) => { | |
const escapedPrefix = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); | |
const matches = [...str.matchAll(RegExp(`(?<=${escapedPrefix})[a-zA-Z0-9-_]+`, 'g'))].map((s) => s[0]); | |
const sortedUniqueStrings = [...new Set(matches)].sort((a, b) => a.localeCompare(b)); | |
sortedUniqueStrings.sort((a, b) => a.localeCompare(b)); | |
const union = [...sortedUniqueStrings].reduce((acc, name) => `${acc}| '${name}'\n`, ''); | |
console.log(union); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment