Add common go types
This commit is contained in:
parent
377e57ee43
commit
af4fc2fb64
4 changed files with 414 additions and 0 deletions
89
internal/common/sort.go
Normal file
89
internal/common/sort.go
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
package common
|
||||
|
||||
import "sort"
|
||||
|
||||
type albumLessFunc func(p1, p2 *Album) bool
|
||||
|
||||
type albumSorter struct {
|
||||
albums []*Album
|
||||
less []albumLessFunc
|
||||
}
|
||||
|
||||
func (s *albumSorter) Len() int {
|
||||
return len(s.albums)
|
||||
}
|
||||
|
||||
func (s *albumSorter) Swap(i, j int) {
|
||||
s.albums[i], s.albums[j] = s.albums[j], s.albums[i]
|
||||
}
|
||||
|
||||
func (s *albumSorter) Less(i, j int) bool {
|
||||
p, q := s.albums[i], s.albums[j]
|
||||
|
||||
var k int
|
||||
for k = 0; k < len(s.less)-1; k++ {
|
||||
less := s.less[k]
|
||||
switch {
|
||||
case less(p, q):
|
||||
return true
|
||||
case less(q, p):
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return s.less[k](p, q)
|
||||
}
|
||||
|
||||
func (s *albumSorter) Sort(albums []*Album) {
|
||||
s.albums = albums
|
||||
sort.Sort(s)
|
||||
}
|
||||
|
||||
func OrderAlbumBy(less ...albumLessFunc) *albumSorter {
|
||||
return &albumSorter{
|
||||
less: less,
|
||||
}
|
||||
}
|
||||
|
||||
func SortAlbums(album []*Album, field string) {
|
||||
title := orderAlbumByTitle
|
||||
artists := orderAlbumByArtists
|
||||
years := orderAlbumByYears
|
||||
modified := orderAlbumByModified
|
||||
|
||||
var sorter *albumSorter
|
||||
switch field {
|
||||
case "artist":
|
||||
sorter = OrderAlbumBy(artists, title, years, modified)
|
||||
case "year":
|
||||
sorter = OrderAlbumBy(years, title, artists, modified)
|
||||
case "modified":
|
||||
sorter = OrderAlbumBy(modified, title, artists, years)
|
||||
default:
|
||||
sorter = OrderAlbumBy(title, artists, years, modified)
|
||||
}
|
||||
|
||||
sorter.Sort(album)
|
||||
}
|
||||
|
||||
func orderAlbumByTitle(c1, c2 *Album) bool {
|
||||
return c1.Title() < c2.Title()
|
||||
}
|
||||
|
||||
func orderAlbumByArtists(left, right *Album) bool {
|
||||
if len(left.Artists()) > 0 && len(right.Artists()) > 0 {
|
||||
return left.Artists()[0] < right.Artists()[0]
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func orderAlbumByYears(c1, c2 *Album) bool {
|
||||
if len(c1.Dates()) > 0 && len(c2.Dates()) > 0 {
|
||||
return c1.Dates()[0] < c2.Dates()[0]
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func orderAlbumByModified(c1, c2 *Album) bool {
|
||||
return c1.LastModified().Before(c2.LastModified())
|
||||
}
|
||||
Loading…
Reference in a new issue