kebabCase function

String kebabCase(
  1. String input
)

Converts a camelCase, PascalCase, or snake_case identifier to kebab-case.

Consecutive uppercase characters are kept together (e.g. HTTPServerhttp-server). Underscores are treated as word boundaries.

Implementation

String kebabCase(String input) {
  if (input.isEmpty) return input;
  final result = StringBuffer();
  var i = 0;
  while (i < input.length) {
    final ch = input[i];
    if (ch == '_') {
      result.write('-');
      i++;
      continue;
    }
    if (_isUpper(ch)) {
      // Gather consecutive uppercase characters
      var end = i + 1;
      while (end < input.length && _isUpper(input[end]) && input[end] != '_') {
        end++;
      }
      // If the uppercase run is followed by a lowercase letter, the last
      // uppercase belongs to the next word.
      if (end > i + 1) {
        result.write(input.substring(i, end - 1).toLowerCase());
        result.write('-');
        i = end - 1;
      } else {
        if (i > 0 && !_isUpper(input[i - 1]) && input[i - 1] != '_') {
          result.write('-');
        }
        result.write(ch.toLowerCase());
        i++;
      }
    } else {
      result.write(ch);
      i++;
    }
  }
  return result.toString();
}