tools: implement tools.Rjust([]string{...})

This commit is contained in:
Taylor Blau 2017-06-13 14:52:21 -06:00
parent 5b573e2592
commit 4f1ae98508
2 changed files with 38 additions and 2 deletions

@ -1,6 +1,9 @@
package tools
import "regexp"
import (
"regexp"
"strings"
)
var (
// quoteFieldRe greedily matches between matching pairs of '', "", or
@ -43,6 +46,24 @@ func QuotedFields(s string) []string {
return out
}
// Rjust returns a copied string slice where each element is right justified to
// match the width of the longest element in the set.
func Rjust(strs []string) []string {
llen := len(Longest(strs))
dup := make([]string, len(strs), cap(strs))
copy(dup, strs)
for i, str := range strs {
width := MaxInt(0, llen-len(str))
padding := strings.Repeat(" ", width)
dup[i] = padding + str
}
return dup
}
// Longest returns the longest element in the string slice in O(n) time and O(1)
// space. If strs is empty or nil, an empty string will be returned.
func Longest(strs []string) string {
@ -52,7 +73,7 @@ func Longest(strs []string) string {
var longest string
var llen int
for _, str := range longest {
for _, str := range strs {
if len(str) >= llen {
longest = str
llen = len(longest)

@ -82,3 +82,18 @@ func TestLongestReturnsLongestString(t *testing.T) {
func TestLongestReturnsLastStringGivenSameLength(t *testing.T) {
assert.Equal(t, "baz", []string{"foo", "bar", "baz"})
}
func TestRjustRightJustifiesString(t *testing.T) {
unjust := []string{
"short",
"longer",
"longest",
}
expected := []string{
" short",
" longer",
"longest",
}
assert.Equal(t, expected, Rjust(unjust))
}