Last active
March 15, 2022 19:26
-
-
Save danmux/30ceb5de2b41f9a964f666a5298cc021 to your computer and use it in GitHub Desktop.
remove front or back
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// remove will remove drop from the start or end of s. | |
// If drop is not found at front or end of s then the | |
// original string is returned. If drop occurs at the | |
// start and end of s, it will only be dropped from the | |
// start. | |
func remove2(s, drop string) string { | |
if strings.HasPrefix(s, drop) { | |
return strings.TrimPrefix(s, drop) | |
} | |
return strings.TrimSuffix(s, drop) | |
} | |
// or providing an explicit location in the string | |
// remove will remove drop from the front of s if fromFront is true, | |
// or from the back of s if false. If drop is not found in the appropriate | |
// place in s, then the original string is returned. | |
func remove(s, drop string, fromFront bool) string { | |
if fromFront { | |
return strings.TrimPrefix(s, drop) | |
} | |
return strings.TrimSuffix(s, drop) | |
} | |
func TestRemove(t *testing.T) { | |
tests := []struct { | |
name string | |
s string | |
drop string | |
fromFont bool | |
expected string | |
}{ | |
{ | |
name: "good_front_drop", | |
s: "foo-bar-bad", | |
drop: "foo-", | |
fromFont: true, | |
expected: "bar-bad", | |
}, | |
{ | |
name: "bad_front_drop", | |
s: "foo-bar-bad", | |
drop: "foo-", | |
fromFont: false, | |
expected: "foo-bar-bad", | |
}, | |
{ | |
name: "missing_front_drop", | |
s: "foo-bar-bad", | |
drop: "flo", | |
fromFont: true, | |
expected: "foo-bar-bad", | |
}, | |
{ | |
name: "good_back_drop", | |
s: "foo-bar-bad", | |
drop: "bad", | |
fromFont: false, | |
expected: "foo-bar-", | |
}, | |
{ | |
name: "bad_back_drop", | |
s: "foo-bar-bad", | |
drop: "bad", | |
fromFont: true, | |
expected: "foo-bar-bad", | |
}, | |
{ | |
name: "missing_back_drop", | |
s: "foo-bar-bad", | |
drop: "bod", | |
fromFont: false, | |
expected: "foo-bar-bad", | |
}, | |
} | |
for _, tt := range tests { | |
t.Run(tt.name, func(t *testing.T) { | |
got := remove(tt.s, tt.drop, tt.fromFont) | |
if got != tt.expected { | |
t.Errorf("got: %q, expected: %q", got, tt.expected) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment