/
blogposts.go
106 lines (78 loc) · 2.07 KB
/
blogposts.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"errors"
)
const validFilenameExtension = ".md"
const couldNotFindPostErrorMessage = "Could not find post"
type BlogPostFilter func(post *BlogPost, index int, stop *bool) bool
type BlogPosts []*BlogPost
func (b BlogPosts) Len() int {
return len(b)
}
func (b BlogPosts) Swap(i, j int) {
b[i], b[j] = b[j], b[i]
}
func (b BlogPosts) Less(i, j int) bool {
// We use "After" instead of "Before" to get posts in descending order
return b[i].Metadata.Date.After(b[j].Metadata.Date)
}
func (b BlogPosts) Filter(filter BlogPostFilter) BlogPosts {
filteredPosts := BlogPosts{}
stop := false
for index, post := range b {
if filter(post, index, &stop) {
filteredPosts = append(filteredPosts, post)
}
if stop {
break
}
}
return filteredPosts
}
func (b BlogPosts) FilteredPosts(term string, start int, count int) (BlogPosts, int) {
var filteredPosts BlogPosts
if len(term) > 0 {
filteredPosts = b.Filter(func(post *BlogPost, index int, stop *bool) bool {
return post.ContainsTerm(term)
})
} else {
filteredPosts = b
}
if start > len(filteredPosts) {
return BlogPosts{}, 0
}
if start+count > len(filteredPosts) {
count = len(filteredPosts) - start
}
return filteredPosts[start : start+count], len(filteredPosts)
}
func (b BlogPosts) PostWithUrl(url string) (*BlogPost, error) {
for _, post := range b {
if post.Url == url {
return post, nil
}
}
err := errors.New(couldNotFindPostErrorMessage)
return nil, err
}
func (b BlogPosts) PostsWithTag(tag string, start int, count int) (BlogPosts, int) {
filteredPosts := b.Filter(func(post *BlogPost, index int, stop *bool) bool {
return post.ContainsTag(tag)
})
if start > len(filteredPosts) {
return BlogPosts{}, 0
}
if start+count > len(filteredPosts) {
count = len(filteredPosts) - start
}
return filteredPosts[start : start+count], len(filteredPosts)
}
func (b BlogPosts) PostWithId(id int) (*BlogPost, error) {
for _, post := range b {
if post.Metadata.Id == id {
return post, nil
}
}
err := errors.New(couldNotFindPostErrorMessage)
return nil, err
}