src

Go monorepo.
Log | Files | Refs

commit b6b9161af11c1ca8a7b9451b926123aedb1413a0
parent ca803f3efcca4a80a0af0ad31e3f295f343c376e
Author: dwrz <dwrz@dwrz.net>
Date:   Mon,  9 Jan 2023 21:09:59 +0000

Add text pkg

Diffstat:
Apkg/text/truncate.go | 11+++++++++++
Apkg/text/wrap.go | 30++++++++++++++++++++++++++++++
2 files changed, 41 insertions(+), 0 deletions(-)

diff --git a/pkg/text/truncate.go b/pkg/text/truncate.go @@ -0,0 +1,11 @@ +package text + +import "strings" + +func Truncate(text string, width int) string { + if len(text) < width { + return text + } + + return strings.TrimSpace(text[:width]) +} diff --git a/pkg/text/wrap.go b/pkg/text/wrap.go @@ -0,0 +1,30 @@ +package text + +import "strings" + +func Wrap(text string, width int) string { + if width < 0 { + return text + } + + var words = strings.Fields(text) + if len(words) == 0 { + return "" + } + + var ( + wrapped = words[0] + remaining = width - len(wrapped) + ) + for _, word := range words[1:] { + if len(word)+1 > remaining { + wrapped += "\n" + word + remaining = width - len(word) + } else { + wrapped += " " + word + remaining -= 1 + len(word) + } + } + + return wrapped +}