Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add Ownable, proper sort by timestamp #8

Merged
merged 11 commits into from
Mar 19, 2024
59 changes: 44 additions & 15 deletions api/p/memeland/memeland.gno
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,6 @@ type Post struct {
UpvoteTracker *avl.Tree // address > struct{}{}
}

type UpvoteSorter []*Post
type DateSorter []*Post

type Memeland struct {
*ownable.Ownable
Posts []*Post
Expand Down Expand Up @@ -103,10 +100,22 @@ func (m *Memeland) GetPostsInRange(startTimestamp, endTimestamp int64, page, pag
switch sortBy {
// Sort by upvote descending
case "UPVOTES":
sort.Sort(UpvoteSorter(filteredPosts))
dateSorter := PostSorter{
posts: filteredPosts,
less: func(i, j int) bool {
return filteredPosts[i].UpvoteTracker.Size() > filteredPosts[j].UpvoteTracker.Size()
},
}
sort.Sort(dateSorter)
default:
// Sort by timestamp, beginning with newest
sort.Sort(DateSorter(filteredPosts))
dateSorter := PostSorter{
posts: filteredPosts,
less: func(i, j int) bool {
return filteredPosts[i].Timestamp.Before(filteredPosts[j].Timestamp)
},
}
sort.Sort(dateSorter)
}

// Pagination
Expand Down Expand Up @@ -189,16 +198,36 @@ func (m *Memeland) getPost(id string) *Post {
return nil
}

// Sort by newest first
func (a DateSorter) Len() int { return len(a) }
func (a DateSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a DateSorter) Less(i, j int) bool {
return a[i].Timestamp.Before(a[j].Timestamp)
type PostSorter struct {
posts []*Post
less func(i, j int) bool
}

func (p PostSorter) Len() int {
return len(p.posts)
}

func (p PostSorter) Swap(i, j int) {
p.posts[i], p.posts[j] = p.posts[j], p.posts[i]
}

// Sort by upvote count
func (a UpvoteSorter) Len() int { return len(a) }
func (a UpvoteSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a UpvoteSorter) Less(i, j int) bool {
return a[i].UpvoteTracker.Size() > a[j].UpvoteTracker.Size()
func (p PostSorter) Less(i, j int) bool {
return p.Less(i, j)
leohhhn marked this conversation as resolved.
Show resolved Hide resolved
}

//type UpvoteSorter []*Post
//type DateSorter []*Post
//
//// Sort by newest first
//func (a DateSorter) Len() int { return len(a) }
//func (a DateSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
//func (a DateSorter) Less(i, j int) bool {
// return a[i].Timestamp.Before(a[j].Timestamp)
//}
//
//// Sort by upvote count
//func (a UpvoteSorter) Len() int { return len(a) }
//func (a UpvoteSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
//func (a UpvoteSorter) Less(i, j int) bool {
// return a[i].UpvoteTracker.Size() > a[j].UpvoteTracker.Size()
//}