Maybe rename whole Elem
to Elm
??
Think about naming...
// ElemByKey takes string and search for the key, and return the value.
// Eg. ElemByKey(`id=123,name=Gon,age=40`, "age", '=', ',') --> "40"
func ElemByKey(s string, key string, sep, delim rune) string {
// Get first delim
cur := 0
foundKey := false
lastIdx := len(s) - 1
var prevC rune
for idx, c := range s {
if foundKey {
if idx == lastIdx {
return s[cur : idx+1] // when [1,2], to select 1,2, s[1:3]; need [:n+1].. therefore
}
if c == delim {
return s[cur:idx]
}
continue
}
if c == sep || c == delim {
if c == sep && s[cur:idx] == key { // sep separates key and value, `abc=123, def=456` --> "="
foundKey = true
}
// delimiter splits diff fields, `abc=123, def=456` --> ","
cur = idx
if idx != lastIdx {
cur += 1
}
prevC = c
continue
}
if prevC == delim {
if c == ' ' {
continue
}
cur = idx
}
prevC = c
}
return ""
}
TEST
t.Run("ElemByKey", func(t *testing.T) {
s := `id=123, name=Gon, age=40,name2=Jon,blank=,age2=100`
gosl.Test(t, "123", gosl.ElemByKey(s, "id", '=', ','))
gosl.Test(t, "Gon", gosl.ElemByKey(s, "name", '=', ','))
gosl.Test(t, "40", gosl.ElemByKey(s, "age", '=', ','))
gosl.Test(t, "Jon", gosl.ElemByKey(s, "name2", '=', ','))
gosl.Test(t, "100", gosl.ElemByKey(s, "age2", '=', ','))
gosl.Test(t, "", gosl.ElemByKey(s, "blank", '=', ','))
})
BENCH
func Benchmark_String_ElemByKey(b *testing.B) {
b.Run("ElemByKey", func(b *testing.B) {
b.ReportAllocs()
s := `id=123, name=Gon, age=40, someLong=,name2=Jon,age2=100`
var out string
for i := 0; i < b.N; i++ {
out = gosl.ElemByKey(s, "age", '=', ',')
}
_ = out
//println(out)
})
}
Feature - New Coded