Skip to content

Commit

Permalink
chore: refactor padding functions (#254)
Browse files Browse the repository at this point in the history
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 <michael.lorant@nine.com.au>
  • Loading branch information
mikelorant committed Jan 31, 2024
1 parent 59874c2 commit 92946d3
Showing 1 changed file with 28 additions and 24 deletions.
52 changes: 28 additions & 24 deletions style.go
Original file line number Diff line number Diff line change
Expand Up @@ -464,36 +464,23 @@ 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)
}

// pad adds padding to either the left or right side of a string.
// Positive values add to the right side while negative values
// add to the left side.
func pad(str string, n int, style *termenv.Style) string {
if n == 0 {
return str
}

sp := strings.Repeat(" ", n)
sp := strings.Repeat(" ", abs(n))
if style != nil {
sp = style.Styled(sp)
}
Expand All @@ -502,8 +489,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')
}
Expand All @@ -525,3 +521,11 @@ func min(a, b int) int {
}
return b
}

func abs(a int) int {
if a < 0 {
return -a
}

return a
}

0 comments on commit 92946d3

Please sign in to comment.