mirror of
https://github.com/nbd-wtf/go-nostr.git
synced 2025-05-11 19:19:58 +02:00
nip54: improve normalization and add tests.
This commit is contained in:
parent
c0f1c4f510
commit
6f32e4da63
@ -1,17 +1,26 @@
|
||||
package nip54
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"golang.org/x/text/transform"
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
var nonLetter = regexp.MustCompile(`\W`)
|
||||
|
||||
func NormalizeIdentifier(name string) string {
|
||||
name = strings.ToLower(name)
|
||||
res, _, _ := transform.Bytes(norm.NFKC, []byte(name))
|
||||
str := nonLetter.ReplaceAllString(string(res), "-")
|
||||
return strings.ToLower(str)
|
||||
runes := []rune(string(res))
|
||||
|
||||
b := make([]rune, len(runes))
|
||||
for i, letter := range runes {
|
||||
if unicode.IsLetter(letter) {
|
||||
b[i] = letter
|
||||
} else {
|
||||
b[i] = '-'
|
||||
}
|
||||
}
|
||||
|
||||
return string(b)
|
||||
}
|
||||
|
23
nip54/nip54_test.go
Normal file
23
nip54/nip54_test.go
Normal file
@ -0,0 +1,23 @@
|
||||
package nip54
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNormalization(t *testing.T) {
|
||||
for _, vector := range []struct {
|
||||
before string
|
||||
after string
|
||||
}{
|
||||
{"hello", "hello"},
|
||||
{"Goodbye", "goodbye"},
|
||||
{"the long and winding road / that leads to your door", "the-long-and-winding-road---that-leads-to-your-door"},
|
||||
{"it's 平仮名", "it-s-平仮名"},
|
||||
} {
|
||||
if norm := NormalizeIdentifier(vector.before); norm != vector.after {
|
||||
fmt.Println([]byte(vector.after), []byte(norm))
|
||||
t.Fatalf("%s: %s != %s", vector.before, norm, vector.after)
|
||||
}
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user