Skip to content

Commit

Permalink
feat: add strings.TrimToOnly
Browse files Browse the repository at this point in the history
  • Loading branch information
zostay committed Dec 4, 2024
1 parent 4717bcf commit 64ff4c6
Show file tree
Hide file tree
Showing 5 changed files with 64 additions and 0 deletions.
35 changes: 35 additions & 0 deletions .idea/golinter.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Changes.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## WIP TBD

* Adding `strings.TrimToOnly`.

## v0.9.1 2024-10-15

* :hammer: Fixed buf in `strings.Indent` that caused a panic if the input string was empty.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ provided tools:
Here's a few additional operations for working with slices of bytes:

* `ContainsOnly(b, chars)`
* `TrimToOnly(b, chars)`
* `FromRange(a, z)`
* `Reverse(b)`
* `Indent(b, indent)`
Expand Down
13 changes: 13 additions & 0 deletions strings/content.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,19 @@ func ContainsOnly(s, chars string) bool {
}) == -1
}

// TrimToOnly returns the string with all characters removed that are not in the
// given set of characters.
func TrimToOnly(s string, chars string) string {
var out []rune
for _, r := range s {
if strings.ContainsRune(chars, r) {
out = append(out, r)
break
}
}
return string(out)
}

type runeSlice []rune

// func (rs runeSlice) Less(i, j int) bool {
Expand Down
11 changes: 11 additions & 0 deletions strings/content_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ func TestContainsOnly(t *testing.T) {
assert.False(t, strings.ContainsOnly("a b c", "abc"))
}

func TestTrimToOnly(t *testing.T) {
t.Parallel()

assert.Equal(t, "abc", strings.TrimToOnly("abc", "abc"))
assert.Equal(t, "a", strings.TrimToOnly("a", "abc"))
assert.Equal(t, "aaaaaabbbbbbccccc", strings.TrimToOnly("aaaaaabbbbbbccccc", "cba"))
assert.Equal(t, "abc", strings.TrimToOnly("a b c", "abc"))
assert.Equal(t, "", strings.TrimToOnly("abc", "def"))
assert.Equal(t, "abde", strings.TrimToOnly("abcdef", "adbe"))
}

func TestFromRange(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 64ff4c6

Please sign in to comment.