Skip to content

Instantly share code, notes, and snippets.

@jomifepe
Last active June 12, 2021 15:23
Show Gist options
  • Save jomifepe/cfd52b52e887e03e815b43afec37deb2 to your computer and use it in GitHub Desktop.
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
/**
* 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