camelToSnake static method

String camelToSnake(
  1. String input
)

Implementation

static String camelToSnake(String input) {
  if (input.isEmpty) return input;

  final buf = StringBuffer();
  for (var i = 0; i < input.length; i++) {
    final char = input[i];

    if (_isUpper(char) && i > 0) {
      final prev = input[i - 1];
      final next = i + 1 < input.length ? input[i + 1] : null;

      // Boundary #1: a lower->upper (or digit->upper) transition, e.g.
      // "userId" -> "user_Id", "item2Name" -> "item2_Name".
      final afterLowerOrDigit = _isLower(prev) || _isDigit(prev);

      // Boundary #2: the end of an acronym run followed by a lowercase
      // letter, e.g. "HTTPServer" -> "HTTP_Server" (split before the "S",
      // not before every capital in "HTTP"). Without this, "HTTPServer"
      // would come out "h_t_t_p_server" instead of "http_server".
      final endOfAcronym = _isUpper(prev) && next != null && _isLower(next);

      if (afterLowerOrDigit || endOfAcronym) {
        buf.write('_');
      }
    }

    buf.write(char.toLowerCase());
  }
  return buf.toString();
}