From 62b8c0e4d180e77072e88915e748d964c3c647e5 Mon Sep 17 00:00:00 2001 From: Michael Lorant Date: Fri, 26 Jan 2024 14:13:36 +1100 Subject: [PATCH] Refactor padding functions The `padLeft` and `padRight` functions were nearly identical and could benefit from being refactored to share common code. A new function called `pad` was added that applies padding based on the sign of the amount of padding needed. A positive value applies padding to the right side while a negative value applies padding to the left side. Issue: #252 Signed-off-by: Michael Lorant --- style.go | 49 +++++++++++++++++++++++++------------------------ 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/style.go b/style.go index 72be9ef3..380d2e00 100644 --- a/style.go +++ b/style.go @@ -464,36 +464,20 @@ func (s Style) applyMargins(str string, inline bool) string { // Apply left padding. func padLeft(str string, n int, style *termenv.Style) string { - if n == 0 { - return str - } - - sp := strings.Repeat(" ", n) - if style != nil { - sp = style.Styled(sp) - } - - b := strings.Builder{} - l := strings.Split(str, "\n") - - for i := range l { - b.WriteString(sp) - b.WriteString(l[i]) - if i != len(l)-1 { - b.WriteRune('\n') - } - } - - return b.String() + return pad(str, -n, style) } // Apply right padding. func padRight(str string, n int, style *termenv.Style) string { + return pad(str, n, style) +} + +func pad(str string, n int, style *termenv.Style) string { if n == 0 || str == "" { return str } - sp := strings.Repeat(" ", n) + sp := strings.Repeat(" ", abs(n)) if style != nil { sp = style.Styled(sp) } @@ -502,8 +486,17 @@ func padRight(str string, n int, style *termenv.Style) string { l := strings.Split(str, "\n") for i := range l { - b.WriteString(l[i]) - b.WriteString(sp) + switch { + // pad right + case n > 0: + b.WriteString(l[i]) + b.WriteString(sp) + // pad left + default: + b.WriteString(sp) + b.WriteString(l[i]) + } + if i != len(l)-1 { b.WriteRune('\n') } @@ -525,3 +518,11 @@ func min(a, b int) int { } return b } + +func abs(a int) int { + if a < 0 { + return -a + } + + return a +}