Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add strings.TrimToOnly #26

Merged
merged 2 commits into from
Dec 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
continue
}
}
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
Loading