Skip to content

Commit

Permalink
sort posts
Browse files Browse the repository at this point in the history
  • Loading branch information
leohhhn committed Nov 13, 2023
1 parent 94e44d7 commit 3bec81d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
11 changes: 10 additions & 1 deletion examples/gno.land/p/demo/blog/blog.gno
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,20 @@ func (b Blog) RenderHome(res *mux.ResponseWriter, req *mux.Request) {
}

res.Write("<div class='columns-3'>")

var sorted []*Post
b.Posts.Iterate("", "", func(key string, value interface{}) bool {
post := value.(*Post)
res.Write(post.RenderListItem())
sorted = append(sorted, post)
return false
})

sorted = mergeSort(sorted)

for _, post := range sorted {
res.Write(post.RenderListItem())
}

res.Write("</div>")

// FIXME: tag list/cloud.
Expand Down
34 changes: 34 additions & 0 deletions examples/gno.land/p/demo/blog/util.gno
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,37 @@ import "strings"
func breadcrumb(parts []string) string {
return "# " + strings.Join(parts, " / ") + "\n\n"
}

func merge(left, right []*Post) []*Post {
result := make([]*Post, 0, len(left)+len(right))

for len(left) > 0 || len(right) > 0 {
if len(left) == 0 {
return append(result, right...)
}
if len(right) == 0 {
return append(result, left...)
}
if left[0].CreatedAt.After(right[0].CreatedAt) {
result = append(result, left[0])
left = left[1:]
} else {
result = append(result, right[0])
right = right[1:]
}
}

return result
}

func mergeSort(posts []*Post) []*Post {
if len(posts) <= 1 {
return posts
}

middle := len(posts) / 2
left := mergeSort(posts[:middle])
right := mergeSort(posts[middle:])

return merge(left, right)
}

0 comments on commit 3bec81d

Please sign in to comment.