From 3bec81d51c99922ce7a86376dc4070080f127133 Mon Sep 17 00:00:00 2001 From: leohhhn Date: Mon, 13 Nov 2023 13:49:45 +0100 Subject: [PATCH] sort posts --- examples/gno.land/p/demo/blog/blog.gno | 11 ++++++++- examples/gno.land/p/demo/blog/util.gno | 34 ++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/examples/gno.land/p/demo/blog/blog.gno b/examples/gno.land/p/demo/blog/blog.gno index 1cf37b7ad3a..78748c97d44 100644 --- a/examples/gno.land/p/demo/blog/blog.gno +++ b/examples/gno.land/p/demo/blog/blog.gno @@ -42,11 +42,20 @@ func (b Blog) RenderHome(res *mux.ResponseWriter, req *mux.Request) { } res.Write("
") + + 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("
") // FIXME: tag list/cloud. diff --git a/examples/gno.land/p/demo/blog/util.gno b/examples/gno.land/p/demo/blog/util.gno index b4a8652af72..bf62c7ff47c 100644 --- a/examples/gno.land/p/demo/blog/util.gno +++ b/examples/gno.land/p/demo/blog/util.gno @@ -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) +}