Skip to content

Commit

Permalink
Add sort.Interface implementation for Feed (#141)
Browse files Browse the repository at this point in the history
Order Feed.Items by oldest to newest publish time.
  • Loading branch information
grafoo committed Mar 31, 2020
1 parent 2251b44 commit 4298e43
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
20 changes: 20 additions & 0 deletions feed.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
// Feed is the universal Feed type that atom.Feed
// and rss.Feed gets translated to. It represents
// a web feed.
// Sorting with sort.Sort will order the Items by
// oldest to newest publish time.
type Feed struct {
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Expand Down Expand Up @@ -82,3 +84,21 @@ type Enclosure struct {
Length string `json:"length,omitempty"`
Type string `json:"type,omitempty"`
}

// Len returns the length of Items.
func (f Feed) Len() int {
return len(f.Items)
}

// Less compares PublishedParsed of Items[i], Items[k]
// and returns true if Items[i] is less than Items[k].
func (f Feed) Less(i, k int) bool {
return f.Items[i].PublishedParsed.Before(
*f.Items[k].PublishedParsed,
)
}

// Swap swaps Items[i] and Items[k].
func (f Feed) Swap(i, k int) {
f.Items[i], f.Items[k] = f.Items[k], f.Items[i]
}
50 changes: 50 additions & 0 deletions feed_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package gofeed_test

import (
"sort"
"testing"
"time"

"github.com/mmcdole/gofeed"
)

func TestFeedSort(t *testing.T) {
oldestItem := &gofeed.Item{
PublishedParsed: &[]time.Time{time.Unix(0, 0)}[0],
}
inbetweenItem := &gofeed.Item{
PublishedParsed: &[]time.Time{time.Unix(1, 0)}[0],
}
newestItem := &gofeed.Item{
PublishedParsed: &[]time.Time{time.Unix(2, 0)}[0],
}

feed := gofeed.Feed{
Items: []*gofeed.Item{
newestItem,
oldestItem,
inbetweenItem,
},
}
expected := gofeed.Feed{
Items: []*gofeed.Item{
oldestItem,
inbetweenItem,
newestItem,
},
}

sort.Sort(feed)

for i, item := range feed.Items {
if !item.PublishedParsed.Equal(
*expected.Items[i].PublishedParsed,
) {
t.Errorf(
"Item PublishedParsed = %s; want %s",
item.PublishedParsed,
expected.Items[i].PublishedParsed,
)
}
}
}

0 comments on commit 4298e43

Please sign in to comment.