Skip to content

Commit

Permalink
Merge pull request #196 from Dean-Coakley/negative-trunc-support
Browse files Browse the repository at this point in the history
Support negative values in trunc
  • Loading branch information
mattfarina authored Oct 2, 2019
2 parents 9c496df + e248bc1 commit bee6f49
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 9 deletions.
18 changes: 12 additions & 6 deletions docs/strings.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,17 @@ trunc 5 "hello world"

The above produces `hello`.

```
trunc -5 "hello world"
```

The above produces `world`.

## abbrev

Truncate a string with ellipses (`...`)

Parameters:
Parameters:
- max length
- the string

Expand Down Expand Up @@ -284,7 +290,7 @@ len $fish | plural "one anchovy" "many anchovies"
```

In the above, if the length of the string is 1, the first argument will be
printed (`one anchovy`). Otherwise, the second argument will be printed
printed (`one anchovy`). Otherwise, the second argument will be printed
(`many anchovies`).

The arguments are:
Expand Down Expand Up @@ -338,10 +344,10 @@ Swap the case of a string using a word based algorithm.

Conversion algorithm:

- Upper case character converts to Lower case
- Title case character converts to Lower case
- Lower case character after Whitespace or at start converts to Title case
- Other Lower case character converts to Upper case
- Upper case character converts to Lower case
- Title case character converts to Lower case
- Lower case character after Whitespace or at start converts to Title case
- Other Lower case character converts to Upper case
- Whitespace is defined by unicode.IsSpace(char).

```
Expand Down
9 changes: 6 additions & 3 deletions strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,13 @@ func strval(v interface{}) string {
}

func trunc(c int, s string) string {
if len(s) <= c {
return s
if c < 0 && len(s)+c > 0 {
return s[len(s)+c:]
}
if c >= 0 && len(s) > c {
return s[:c]
}
return s[0:c]
return s
}

func join(sep string, v interface{}) string {
Expand Down
12 changes: 12 additions & 0 deletions strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@ func TestTrunc(t *testing.T) {
if err := runt(tpl, "foo"); err != nil {
t.Error(err)
}
tpl = `{{ "baaaaaar" | trunc -3 }}`
if err := runt(tpl, "aar"); err != nil {
t.Error(err)
}
tpl = `{{ "baaaaaar" | trunc -999 }}`
if err := runt(tpl, "baaaaaar"); err != nil {
t.Error(err)
}
tpl = `{{ "baaaaaz" | trunc 0 }}`
if err := runt(tpl, ""); err != nil {
t.Error(err)
}
}

func TestQuote(t *testing.T) {
Expand Down

0 comments on commit bee6f49

Please sign in to comment.