Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Speed up/reduce allocations by using strings.Map #8

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 17 additions & 14 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,26 @@
// are unique, that responsibility falls on the caller.
package sanitized_anchor_name // import "github.com/shurcooL/sanitized_anchor_name"

import "unicode"
import (
"strings"
"unicode"
)

// Create returns a sanitized anchor name for the given text.
func Create(text string) string {
var anchorName []rune
var futureDash = false
for _, r := range text {
switch {
case unicode.IsLetter(r) || unicode.IsNumber(r):
if futureDash && len(anchorName) > 0 {
anchorName = append(anchorName, '-')
}
futureDash = false
anchorName = append(anchorName, unicode.ToLower(r))
default:
futureDash = true
var hasRunes bool
var prevDash bool
fn := func(r rune) rune {
if unicode.IsLetter(r) || unicode.IsNumber(r) {
hasRunes = true
prevDash = false
return unicode.ToLower(r)
}
if hasRunes && !prevDash {
prevDash = true
return '-'
}
return -1
}
return string(anchorName)
return strings.TrimRight(strings.Map(fn, text), "-")
}