diff options
| author | James Mills <prologic@shortcircuit.net.au> | 2020-03-25 16:22:41 +1000 |
|---|---|---|
| committer | James Mills <prologic@shortcircuit.net.au> | 2020-03-25 16:22:41 +1000 |
| commit | 9fa34273082e588f8876c4f4d1f658f4b3590e92 (patch) | |
| tree | 3b99fc82d67b857e9dbe747d1bfc330aa21995e9 /media | |
| parent | 2c8af031648d110148dfe672c4fc3063f1743374 (diff) | |
Add trending and ability to sort playlist by views
Diffstat (limited to 'media')
| -rw-r--r-- | media/library.go | 2 | ||||
| -rw-r--r-- | media/playlist.go | 49 |
2 files changed, 39 insertions, 12 deletions
diff --git a/media/library.go b/media/library.go index 87fb223..b255322 100644 --- a/media/library.go +++ b/media/library.go @@ -6,7 +6,6 @@ import ( "log" "path" "path/filepath" - "sort" "strings" "sync" ) @@ -117,6 +116,5 @@ func (lib *Library) Playlist() Playlist { pl[i] = v i++ } - sort.Sort(pl) return pl } diff --git a/media/playlist.go b/media/playlist.go index cf8edcf..ccfcc79 100644 --- a/media/playlist.go +++ b/media/playlist.go @@ -1,19 +1,48 @@ package media -// Playlist holds an array of videos capable of sorting by Timestamp. +import ( + "sort" +) + type Playlist []*Video -// Len returns length of array (for sorting). -func (p Playlist) Len() int { - return len(p) +// By is the type of a "less" function that defines the ordering of its Playlist arguments. +type By func(p1, p2 *Video) bool + +// Sort is a method on the function type, By, that sorts the argument slice according to the function. +func (by By) Sort(pl Playlist) { + ps := &playlistSorter{ + pl: pl, + by: by, // The Sort method's receiver is the function (closure) that defines the sort order. + } + sort.Sort(ps) +} + +// playlistSorter joins a By function and a slice of Playlist to be sorted. +type playlistSorter struct { + pl Playlist + by func(p1, p2 *Video) bool // Closure used in the Less method. +} + +// Len is part of sort.Interface. +func (s *playlistSorter) Len() int { + return len(s.pl) +} + +// Swap is part of sort.Interface. +func (s *playlistSorter) Swap(i, j int) { + s.pl[i], s.pl[j] = s.pl[j], s.pl[i] +} + +// Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter. +func (s *playlistSorter) Less(i, j int) bool { + return s.by(s.pl[i], s.pl[j]) } -// Swap swaps two values in array by index (for sorting). -func (p Playlist) Swap(i, j int) { - p[i], p[j] = p[j], p[i] +func SortByTimestamp(v1, v2 *Video) bool { + return v1.Timestamp.After(v2.Timestamp) } -// Less returns true if p[i] Timestamp is after p[j] (for sorting). -func (p Playlist) Less(i, j int) bool { - return p[i].Timestamp.After(p[j].Timestamp) +func SortByViews(v1, v2 *Video) bool { + return v1.Views < v2.Views } |
