diff --git a/sorting/streams.go b/sorting/streams.go index 9cb5e3b..083598d 100644 --- a/sorting/streams.go +++ b/sorting/streams.go @@ -5,12 +5,6 @@ type IsGreaterer interface { IsGreater(e IsGreaterer) bool } -type alwaysBigger struct{} - -func (a *alwaysBigger) IsGreater(e IsGreaterer) bool { - return e != nil -} - type Stream chan IsGreaterer type streamOutput struct { @@ -76,7 +70,11 @@ func prependValueToEachStream(streams []Stream, values []IsGreaterer) []Stream { func getSmallestElement(arr []IsGreaterer) (IsGreaterer, int) { smallest, idx := arr[0], 0 for i, elm := range arr { - if smallest.IsGreater(elm) { + if smallest == nil { + smallest = elm + idx = i + } + if elm != nil && smallest.IsGreater(elm) { smallest = elm idx = i } @@ -100,26 +98,27 @@ func getSmallerStreamWithSecondSmallestElementWithAllTheOthersGreaterStreams(str _, smallestStreamIndex := getSmallestElement(firstElements) secondSmallestItem, _ := getSecondSmallestElement(firstElements) - if secondSmallestItem == nil { - return streams[smallestStreamIndex], nil, []Stream{} - } return streams[smallestStreamIndex], secondSmallestItem, allStreamsButOne(streams, smallestStreamIndex) } +func outputToStream(input, output Stream) { + for e := range input { + output <- e + } + close(output) +} + func sortStreamInChannel(o Stream, streams []Stream) { if len(streams) == 1 { - for e := range streams[0] { - o <- e - } - close(o) + outputToStream(streams[0], o) return } smallestStream, secondSmallestItem, greaterStreams := getSmallerStreamWithSecondSmallestElementWithAllTheOthersGreaterStreams(streams) if secondSmallestItem == nil { - sortStreamInChannel(o, append(greaterStreams, smallestStream)) + sortStreamInChannel(o, []Stream{smallestStream}) return - } + for elm := range smallestStream { if !elm.IsGreater(secondSmallestItem) { o <- elm diff --git a/sorting/streams_test.go b/sorting/streams_test.go index 055ace8..c087386 100644 --- a/sorting/streams_test.go +++ b/sorting/streams_test.go @@ -153,8 +153,23 @@ func TestSortStreams(t *testing.T) { t.Error() } + if s := SortStreams(CreateStream()); !streamEqual(s) { + t.Error() + } + if s := SortStreams(CreateStream(1, 4), CreateStream(0, 5)); !streamEqual(s, 0, 1, 4, 5) { t.Error() } + if s := SortStreams(CreateStream(1, 2), CreateStream(3, 4), CreateStream(5, 6)); !streamEqual(s, 1, 2, 3, 4, 5, 6) { + t.Error() + } + + if s := SortStreams(CreateStream(1, 2), CreateStream()); !streamEqual(s, 1, 2) { + t.Error() + } + if s := SortStreams(CreateStream(), CreateStream(1, 2)); !streamEqual(s, 1, 2) { + t.Error() + } + }