summaryrefslogtreecommitdiff
path: root/strings
diff options
context:
space:
mode:
Diffstat (limited to 'strings')
-rw-r--r--strings/strings.go11
-rw-r--r--strings/strings_test.go9
2 files changed, 20 insertions, 0 deletions
diff --git a/strings/strings.go b/strings/strings.go
index 1ca3146a..3b90c83e 100644
--- a/strings/strings.go
+++ b/strings/strings.go
@@ -22,3 +22,14 @@ func Indent(width int, indent, s string) string {
}
return string(res)
}
+
+// Trunc - truncate a string to the given length
+func Trunc(length int, s string) string {
+ if length < 0 {
+ return s
+ }
+ if len(s) <= length {
+ return s
+ }
+ return s[0:length]
+}
diff --git a/strings/strings_test.go b/strings/strings_test.go
index 6ee4064d..ad32e3f6 100644
--- a/strings/strings_test.go
+++ b/strings/strings_test.go
@@ -16,3 +16,12 @@ func TestIndent(t *testing.T) {
assert.Equal(t, " foo", Indent(1, " ", "foo"))
assert.Equal(t, " foo", Indent(3, " ", "foo"))
}
+
+func TestTrunc(t *testing.T) {
+ assert.Equal(t, "", Trunc(5, ""))
+ assert.Equal(t, "", Trunc(0, "hello, world"))
+ assert.Equal(t, "hello", Trunc(5, "hello, world"))
+ assert.Equal(t, "hello, world", Trunc(12, "hello, world"))
+ assert.Equal(t, "hello, world", Trunc(42, "hello, world"))
+ assert.Equal(t, "hello, world", Trunc(-1, "hello, world"))
+}