summaryrefslogtreecommitdiff
path: root/strings
diff options
context:
space:
mode:
authorDave Henderson <dhenderson@gmail.com>2018-05-07 22:05:01 -0400
committerDave Henderson <dhenderson@gmail.com>2018-05-07 22:17:54 -0400
commit2ef052a2d56efc27c64568e65ed3122877573d17 (patch)
tree2ebf44c73fa802c615707dec5dd65c2b9a286091 /strings
parent85eae90d133f2bf13916f39f256142b3077625fa (diff)
Adding strings.Trunc and strings.Abbrev
Signed-off-by: Dave Henderson <dhenderson@gmail.com>
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"))
+}