tools: implement tools.Longest

This commit is contained in:
Taylor Blau 2017-06-13 14:52:08 -06:00
parent fce104a5ee
commit 5b573e2592
2 changed files with 31 additions and 0 deletions

@ -42,3 +42,22 @@ func QuotedFields(s string) []string {
return out return out
} }
// 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 {
if len(strs) == 0 {
return ""
}
var longest string
var llen int
for _, str := range longest {
if len(str) >= llen {
longest = str
llen = len(longest)
}
}
return longest
}

@ -70,3 +70,15 @@ func TestQuotedFields(t *testing.T) {
c.Assert(t) c.Assert(t)
} }
} }
func TestLongestReturnsEmptyStringGivenEmptySet(t *testing.T) {
assert.Equal(t, "", Longest(nil))
}
func TestLongestReturnsLongestString(t *testing.T) {
assert.Equal(t, "longest", []string{"short", "longer", "longest"})
}
func TestLongestReturnsLastStringGivenSameLength(t *testing.T) {
assert.Equal(t, "baz", []string{"foo", "bar", "baz"})
}