Skip to content

Commit

Permalink
CompareEvent/Ptr/Reverse utils.
Browse files Browse the repository at this point in the history
  • Loading branch information
fiatjaf committed Sep 30, 2024
1 parent fe35088 commit d29025e
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
41 changes: 41 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,44 @@ func CompareEvent(a, b Event) int {
}
return cmp.Compare(a.CreatedAt, b.CreatedAt)
}

func CompareEventReverse(b, a Event) int {
if a.CreatedAt == b.CreatedAt {
return strings.Compare(a.ID, b.ID)
}
return cmp.Compare(a.CreatedAt, b.CreatedAt)
}

func CompareEventPtr(a, b *Event) int {
if a == nil {
if b == nil {
return 0
} else {
return -1
}
} else if b == nil {
return 1
}

if a.CreatedAt == b.CreatedAt {
return strings.Compare(a.ID, b.ID)
}
return cmp.Compare(a.CreatedAt, b.CreatedAt)
}

func CompareEventPtrReverse(b, a *Event) int {
if a == nil {
if b == nil {
return 0
} else {
return -1
}
} else if b == nil {
return 1
}

if a.CreatedAt == b.CreatedAt {
return strings.Compare(a.ID, b.ID)
}
return cmp.Compare(a.CreatedAt, b.CreatedAt)
}
52 changes: 52 additions & 0 deletions utils_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package nostr

import (
"slices"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestIsValidRelayURL(t *testing.T) {
Expand All @@ -24,3 +26,53 @@ func TestIsValidRelayURL(t *testing.T) {
assert.Equal(t, test.want, got)
}
}

func TestEventsCompare(t *testing.T) {
list := []Event{
{CreatedAt: 12},
{CreatedAt: 8},
{CreatedAt: 26},
{CreatedAt: 1},
}

slices.SortFunc(list, CompareEvent)
require.Equal(t, []Event{
{CreatedAt: 1},
{CreatedAt: 8},
{CreatedAt: 12},
{CreatedAt: 26},
}, list)

slices.SortFunc(list, CompareEventReverse)
require.Equal(t, []Event{
{CreatedAt: 26},
{CreatedAt: 12},
{CreatedAt: 8},
{CreatedAt: 1},
}, list)
}

func TestEventsComparePtr(t *testing.T) {
list := []*Event{
{CreatedAt: 12},
{CreatedAt: 8},
{CreatedAt: 26},
{CreatedAt: 1},
}

slices.SortFunc(list, CompareEventPtr)
require.Equal(t, []*Event{
{CreatedAt: 1},
{CreatedAt: 8},
{CreatedAt: 12},
{CreatedAt: 26},
}, list)

slices.SortFunc(list, CompareEventPtrReverse)
require.Equal(t, []*Event{
{CreatedAt: 26},
{CreatedAt: 12},
{CreatedAt: 8},
{CreatedAt: 1},
}, list)
}

0 comments on commit d29025e

Please sign in to comment.