tools: implement tools.Longest
This commit is contained in:
parent
fce104a5ee
commit
5b573e2592
@ -42,3 +42,22 @@ func QuotedFields(s string) []string {
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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"})
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user