parseTypeName method

(String, List) parseTypeName(
  1. dynamic name
)

Parse a type name and get the type's generics.

final (typeName, typeParams) = parseTypeName('Option<Coin<SUI>>');
// typeName: Option
// typeParams: [ 'Coin<SUI>' ]

Implementation

(String, List<dynamic>) parseTypeName(TypeName name) {
  if (name is Iterable) {
    final nameList = name.toList();
    return (nameList[0], nameList.sublist(1));
  }

  if (name is! String) {
    throw ArgumentError("Illegal type passed as a name of the type: $name");
  }

  final (left, right) = schema.genericSeparators ?? ("<", ">");

  final l_bound = name.indexOf(left);
  final r_bound = name.split("").reversed.toList().indexOf(right);

  // if there are no generics - exit gracefully.
  if (l_bound == -1 && r_bound == -1) {
    return (name, []);
  }

  // if one of the bounds is not defined - throw an Error.
  if (l_bound == -1 || r_bound == -1) {
    throw ArgumentError("Unclosed generic in name '$name'");
  }

  final typeName = name.substring(0, l_bound);
  final params = name
    .substring(l_bound + 1, name.length - r_bound - 1)
    .split(",")
    .map((e) => e.trim())
    .toList();

  return (typeName, params);
}