Last active
February 12, 2019 14:52
-
-
Save lukepighetti/a4b516cf0a5f5e2a27f67e85f7d0dda5 to your computer and use it in GitHub Desktop.
Convert a list of SNAKE_CASE strings into a Dart enum/map declaration
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
void main() { | |
const enumName = "Status"; | |
const text = """ | |
PRE_TRADING, TRADING, POST_TRADING, END_OF_DAY, HALT, AUCTION_MATCH, BREAK | |
"""; | |
final valueList = _sanitize(text); | |
final camelList = _camelize(valueList); | |
print(_buildEnumDeclaration(enumName, camelList)); | |
print(_buildMapDeclaration(enumName, valueList, camelList)); | |
} | |
/// Sanitizes a string list of keys separated by commas and whitespace | |
List<String> _sanitize(String s) => s.replaceAll(RegExp(r'\s'), "").split(','); | |
/// Camelizes a list of SNAKE_CASE_STRINGS | |
List<String> _camelize(List<String> list) => list.map((l) { | |
final words = l.split("_"); | |
final firstWord = words.first.toLowerCase(); | |
final lastWords = words.sublist(1).map((w) => _capitalize(w)); | |
return firstWord + lastWords.join(""); | |
}).toList(); | |
/// Generates a Dart enum declaration | |
String _buildEnumDeclaration(String enumName, List<String> camelList) => """ | |
enum $enumName { | |
${camelList.join(",\n ")} | |
} | |
"""; | |
/// Generates a Dart map declaration for converting string values to enums | |
String _buildMapDeclaration( | |
String enumName, List<String> list, List<String> camelList) { | |
final entries = Map.fromIterables(list, camelList).entries; | |
return """ | |
const ${enumName.toLowerCase()}Map = <String, $enumName>{ | |
${entries.map((e) => "'${e.key}': $enumName.${e.value}").join(",\n ")} | |
}; | |
"""; | |
} | |
/// Capitalize a string | |
String _capitalize(String s) => | |
s[0].toUpperCase() + s.substring(1).toLowerCase(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
DartPad:
https://dartpad.dartlang.org/a4b516cf0a5f5e2a27f67e85f7d0dda5
Input:
Status
PRE_TRADING, TRADING, POST_TRADING, END_OF_DAY, HALT, AUCTION_MATCH, BREAK
Output:
Does not filter reserved keywords like "break"