From 9fa34273082e588f8876c4f4d1f658f4b3590e92 Mon Sep 17 00:00:00 2001 From: James Mills Date: Wed, 25 Mar 2020 16:22:41 +1000 Subject: Add trending and ability to sort playlist by views --- media/playlist.go | 49 +++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 10 deletions(-) (limited to 'media/playlist.go') 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 } -- cgit v1.2.3