tpl/strings: Add strings.Count
authorBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Fri, 3 Jul 2020 08:34:40 +0000 (10:34 +0200)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Fri, 3 Jul 2020 08:35:46 +0000 (10:35 +0200)
Fixes #7453

tpl/strings/init.go
tpl/strings/strings.go

index 7e638e6fc6a2b2c0060303726cacf5a4fd310f2d..fe0cff83b416185968b269d76ab6b3df7e5f59c8 100644 (file)
@@ -51,6 +51,13 @@ func init() {
                        [][2]string{},
                )
 
+               ns.AddMethodMapping(ctx.Count,
+                       nil,
+                       [][2]string{
+                               {`{{"aabab" | strings.Count "a" }}`, `3`},
+                       },
+               )
+
                ns.AddMethodMapping(ctx.FindRE,
                        []string{"findRE"},
                        [][2]string{
index e807fe6fa347f786d57309cfdfaf852d1619e8a8..d78234e415cd5ce560d4d46a213f09e522145b12 100644 (file)
@@ -18,6 +18,7 @@ import (
        "errors"
        "fmt"
        "html/template"
+       "strings"
 
        _strings "strings"
        "unicode/utf8"
@@ -90,6 +91,20 @@ func (ns *Namespace) CountWords(s interface{}) (int, error) {
        return counter, nil
 }
 
+// Count counts the number of non-overlapping instances of substr in s.
+// If substr is an empty string, Count returns 1 + the number of Unicode code points in s.
+func (ns *Namespace) Count(substr, s interface{}) (int, error) {
+       substrs, err := cast.ToStringE(substr)
+       if err != nil {
+               return 0, _errors.Wrap(err, "Failed to convert substr to string")
+       }
+       ss, err := cast.ToStringE(s)
+       if err != nil {
+               return 0, _errors.Wrap(err, "Failed to convert s to string")
+       }
+       return strings.Count(ss, substrs), nil
+}
+
 // Chomp returns a copy of s with all trailing newline characters removed.
 func (ns *Namespace) Chomp(s interface{}) (interface{}, error) {
        ss, err := cast.ToStringE(s)