Skip to content

Commit

Permalink
refactor: Function capitalize word (#460)
Browse files Browse the repository at this point in the history
* feat: implement function capitalize_word

* test: add test TestCapitalizeWordAction

fix: in CapitalizeWord add strings.Join(capWords, " ") to return.

* fix: in CapitalizeWord use Fields instead of Split to takecare of dup spaces.

* fix: redo function to keep spaces and handle unicode, add tests.

* fix: update comment for NewCapitalizeWordAction

* refactor: better readability, cleaner code in CapitalizeWord. Add test case.
  • Loading branch information
allensuvorov authored Feb 24, 2023
1 parent 46e8c07 commit 6ce2c8b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,16 @@ func TestCapitalizeWordAction(t *testing.T) {
So(err, ShouldBeNil)
So(e.Extensions()["test"], ShouldEqual, "A")
})
Convey("test capitalize word: leading symbols", t, func() {
a, err := runtime.NewAction([]interface{}{funcName, "$.test"})
So(err, ShouldBeNil)
e := cetest.MinEvent()
e.SetExtension("test", "let 'em go")
ceCtx := &context.EventContext{
Event: &e,
}
err = a.Execute(ceCtx)
So(err, ShouldBeNil)
So(e.Extensions()["test"], ShouldEqual, "Let 'em Go")
})
}
25 changes: 11 additions & 14 deletions internal/primitive/transform/function/strings_functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,21 +125,18 @@ var CapitalizeWord = function{
fixedArgs: []common.Type{common.String},
fn: func(args []interface{}) (interface{}, error) {
value, _ := args[0].(string)
if len(value) == 0 {
return value, nil
}
if len(value) == 1 {
return strings.ToUpper(string(value[0])), nil
}
capWords := make([]rune, 0, len([]rune(value)))
prev := ' '
for _, v := range value {
if v != ' ' && prev == ' ' {
v = unicode.ToUpper(v)
rs := []rune(value)
inWord := false
for i, r := range rs {
if !unicode.IsSpace(r) {
if !inWord {
rs[i] = unicode.ToTitle(r)
}
inWord = true
} else {
inWord = false
}
capWords = append(capWords, v)
prev = v
}
return string(capWords), nil
return string(rs), nil
},
}

0 comments on commit 6ce2c8b

Please sign in to comment.