From 6711cbb69e83c6add47ca3173946483596bbca12 Mon Sep 17 00:00:00 2001 From: Anton Novojilov Date: Sun, 27 Dec 2015 15:05:23 +0100 Subject: [PATCH] Added methods Head and Tail to strutil --- changelog.md | 5 +++++ strutil/strutil.go | 30 ++++++++++++++++++++++++++++++ strutil/strutil_test.go | 16 ++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/changelog.md b/changelog.md index 6375bea6..9843df04 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,10 @@ ## Changelog +#### v1.3.1 + +* `[strutil]` Added method Head for subtraction first symbols from the string +* `[strutil]` Added method Tail for subtraction last symbols from the string + #### v1.3 * `[system]` Fixed major bug with OS X compatibility diff --git a/strutil/strutil.go b/strutil/strutil.go index 67c72010..245c04bb 100644 --- a/strutil/strutil.go +++ b/strutil/strutil.go @@ -80,3 +80,33 @@ func Ellipsis(s string, maxSize int) string { return s } + +// Head return n first symbols from given string +func Head(s string, n int) string { + if s == "" || n <= 0 { + return "" + } + + l := len(s) + + if l <= n { + return s + } + + return s[:n] +} + +// Tail return n last symbols from given string +func Tail(s string, n int) string { + if s == "" || n <= 0 { + return "" + } + + l := len(s) + + if l <= n { + return s + } + + return s[n:] +} diff --git a/strutil/strutil_test.go b/strutil/strutil_test.go index 0e5450ec..ac87134a 100644 --- a/strutil/strutil_test.go +++ b/strutil/strutil_test.go @@ -49,3 +49,19 @@ func (s *StrUtilSuite) TestEllipsis(c *C) { c.Assert(Ellipsis("Test1234", 8), Equals, "Test1234") c.Assert(Ellipsis("Test1234test", 8), Equals, "Test1...") } + +func (s *StrUtilSuite) TestHead(c *C) { + c.Assert(Head("", 1), Equals, "") + c.Assert(Head("ABCD1234", 0), Equals, "") + c.Assert(Head("ABCD1234", -10), Equals, "") + c.Assert(Head("ABCD1234", 4), Equals, "ABCD") + c.Assert(Head("ABCD1234", 100), Equals, "ABCD1234") +} + +func (s *StrUtilSuite) TestTail(c *C) { + c.Assert(Tail("", 1), Equals, "") + c.Assert(Tail("ABCD1234", 0), Equals, "") + c.Assert(Tail("ABCD1234", -10), Equals, "") + c.Assert(Tail("ABCD1234", 4), Equals, "1234") + c.Assert(Tail("ABCD1234", 100), Equals, "ABCD1234") +}