Skip to content

Commit 1d3007f

Browse files
authored
Merge pull request #83 from AleFossa/main
Adding Truncate methods to stringsutil
2 parents 2a193b5 + c27309c commit 1d3007f

2 files changed

Lines changed: 31 additions & 0 deletions

File tree

strings/stringsutil.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,3 +245,11 @@ func LongestRepeatingSequence(s string) LongestSequence {
245245
}
246246
return LongestSequence{Sequence: res, Count: resCount}
247247
}
248+
249+
// Truncate a string to max length
250+
func Truncate(data string, maxSize int) string {
251+
if maxSize >= 0 && len(data) > maxSize {
252+
return data[:maxSize]
253+
}
254+
return data
255+
}

strings/stringsutil_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,3 +288,26 @@ func TestLongestRepeatingSequence(t *testing.T) {
288288
require.Equalf(t, test.expected, result.Sequence, "test: %s, expected %q, got: %s", test.s, test.expected, result.Sequence)
289289
}
290290
}
291+
292+
type truncateTest struct {
293+
test string
294+
maxSize int
295+
result string
296+
}
297+
298+
func TestTruncate(t *testing.T) {
299+
tests := []truncateTest{
300+
{test: "abcd", maxSize: -1, result: "abcd"},
301+
{test: "abcd", maxSize: 0, result: ""},
302+
{test: "abcde", maxSize: 3, result: "abc"},
303+
{test: "abcdef", maxSize: 8, result: "abcdef"},
304+
{test: "abcdefg", maxSize: 6, result: "abcdef"},
305+
{test: "aaaa", maxSize: 20, result: "aaaa"},
306+
{test: "aaaa", maxSize: 4, result: "aaaa"},
307+
}
308+
309+
for _, test := range tests {
310+
res := Truncate(test.test, test.maxSize)
311+
require.Equalf(t, test.result, res, "test:%s maxsize: %d result: %s", test.test, test.maxSize, res)
312+
}
313+
}

0 commit comments

Comments
 (0)