-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathposts.go
56 lines (44 loc) · 1.2 KB
/
posts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package blawg
import "sort"
// Posts represents a slice of []Post. It is used for default sorting by date
// and adds some methods used in the templates.
type Posts []Post
func (ps Posts) Len() int {
return len(ps)
}
func (ps Posts) Less(i, j int) bool {
return ps[i].Date.After(ps[j].Date)
}
func (ps Posts) Swap(i, j int) {
ps[i], ps[j] = ps[j], ps[i]
}
// Reverse returns a copy of the Posts, sorted into reverse date order (earliest
// first).
func (ps Posts) Reverse() Posts {
reversedList := make(Posts, len(ps))
copy(reversedList, ps)
sort.Sort(sort.Reverse(reversedList))
return reversedList
}
// Take returns a slice of the first n Posts.
func (ps Posts) Take(n int) Posts {
return ps[:n]
}
// Drop returns a slice of Posts, without the first n.
func (ps Posts) Drop(n int) Posts {
return ps[n:]
}
// SortPostsByDate sorts a list of Posts in place by date order.
func SortPostsByDate(ps *Posts) {
sort.Sort(ps)
}
// Published returns a copy of the Posts, filtering out the unpublished posts
func (ps Posts) Published() Posts {
var onlyPublished = make(Posts, len(ps))
for _, post := range ps {
if post.Published {
onlyPublished = append(onlyPublished, post)
}
}
return onlyPublished
}