Skip to content

Instantly share code, notes, and snippets.

@lukepighetti
Last active February 12, 2019 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukepighetti/a4b516cf0a5f5e2a27f67e85f7d0dda5 to your computer and use it in GitHub Desktop.
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
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();
@lukepighetti
Copy link
Author

lukepighetti commented Feb 12, 2019

DartPad:

https://dartpad.dartlang.org/a4b516cf0a5f5e2a27f67e85f7d0dda5

Input:

Status
PRE_TRADING, TRADING, POST_TRADING, END_OF_DAY, HALT, AUCTION_MATCH, BREAK

Output:

enum Status {
  preTrading,
  trading,
  postTrading,
  endOfDay,
  halt,
  auctionMatch,
  break
}
  
const statusMap = <String, Status>{
  'PRE_TRADING': Status.preTrading,
  'TRADING': Status.trading,
  'POST_TRADING': Status.postTrading,
  'END_OF_DAY': Status.endOfDay,
  'HALT': Status.halt,
  'AUCTION_MATCH': Status.auctionMatch,
  'BREAK': Status.break
};

Does not filter reserved keywords like "break"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment