From 51a79a3dce9c992db2336ee78bee3e3dd78880b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=83=9E=E3=83=AA=E3=82=A6=E3=82=B9?= Date: Fri, 28 Jan 2022 23:18:39 -0500 Subject: [PATCH] Implemented sorting by latest reply in thread --- database/database.go | 27 ++++++++++++++++++++++----- models/article.go | 4 +++- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/database/database.go b/database/database.go index babaeac..4bfdd44 100644 --- a/database/database.go +++ b/database/database.go @@ -257,15 +257,32 @@ func (db *Database) ListArticles() ([]*models.Article, []*models.Article, error) var articlesRoots []*models.Article for i := 0; i < len(articles); i++ { if articles[i].InReplyToID != "" { - if _, exist := articlesMap[articles[i].InReplyToID]; exist == true { - (*articlesMap[articles[i].InReplyToID]).Replies = - append((*articlesMap[articles[i].InReplyToID]).Replies, articles[i]) + inReplyTo := articles[i].InReplyToID + if _, exist := articlesMap[inReplyTo]; exist == true { + + (*articlesMap[inReplyTo]).Replies = + append((*articlesMap[inReplyTo]).Replies, articles[i]) + (*articlesMap[inReplyTo]).LatestReply = articles[i].Date + continue } - } else { - articlesRoots = append(articlesRoots, articles[i]) } + articlesRoots = append(articlesRoots, articles[i]) } + sort.SliceStable(articlesRoots, func(i, j int) bool { + iLatest := articlesRoots[i].LatestReply + if iLatest <= 0 { + iLatest = articlesRoots[i].Date + } + + jLatest := articlesRoots[j].LatestReply + if jLatest <= 0 { + jLatest = articlesRoots[j].Date + } + + return iLatest > jLatest + }) + return articles, articlesRoots, nil } diff --git a/models/article.go b/models/article.go index 8f0a21a..97b45b8 100644 --- a/models/article.go +++ b/models/article.go @@ -18,7 +18,9 @@ type Article struct { Body string `mapstructure:"body" json:"-" validate:"required,min=3,max=524288"` Replies []*Article `mapstructure:"-" json:"-" validate:"-"` - Read bool `mapstructure:"-" json:"read" validate:"-"` + LatestReply int64 `mapstructure:"-" json:"-" validate:"-"` + + Read bool `mapstructure:"-" json:"read" validate:"-"` } func NewArticle() (*Article) {