From d29025e958231e9950d046010423dee4975fb3f1 Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Mon, 30 Sep 2024 00:39:26 -0300 Subject: [PATCH] CompareEvent/Ptr/Reverse utils. --- utils.go | 41 ++++++++++++++++++++++++++++++++++++++++ utils_test.go | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) diff --git a/utils.go b/utils.go index 984204b..165f31a 100644 --- a/utils.go +++ b/utils.go @@ -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) +} diff --git a/utils_test.go b/utils_test.go index 89e4056..1b850ee 100644 --- a/utils_test.go +++ b/utils_test.go @@ -1,9 +1,11 @@ package nostr import ( + "slices" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIsValidRelayURL(t *testing.T) { @@ -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) +}