github.com/markusbkk/elvish@v0.0.0-20231204143114-91dc52438621/pkg/strutil/camel_to_dashed.go (about)

     1  package strutil
     2  
     3  import (
     4  	"strings"
     5  	"unicode"
     6  )
     7  
     8  // CamelToDashed converts a CamelCaseIdentifier to a dash-separated-identifier,
     9  // or a camelCaseIdentifier to a -dash-separated-identifier. All-cap words
    10  // are converted to lower case; HTTP becomes http and HTTPRequest becomes
    11  // http-request.
    12  func CamelToDashed(camel string) string {
    13  	var sb strings.Builder
    14  	runes := []rune(camel)
    15  	for i, r := range runes {
    16  		if (i == 0 && unicode.IsLower(r)) ||
    17  			(0 < i && i < len(runes)-1 &&
    18  				unicode.IsUpper(r) && unicode.IsLower(runes[i+1])) {
    19  			sb.WriteRune('-')
    20  		}
    21  		sb.WriteRune(unicode.ToLower(r))
    22  	}
    23  	return sb.String()
    24  }