mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2026-09-13 22:05:07 +00:00
export event comparator.
This commit is contained in:
+17
-1
@@ -1,5 +1,21 @@
|
||||
import { test, expect } from 'bun:test'
|
||||
import { sortEvents } from './core.ts'
|
||||
import { compareEvents, sortEvents } from './core.ts'
|
||||
|
||||
test('compareEvents', () => {
|
||||
const event = {
|
||||
id: 'abc123',
|
||||
pubkey: 'key1',
|
||||
created_at: 1620000000,
|
||||
kind: 1,
|
||||
tags: [],
|
||||
content: 'Hello',
|
||||
sig: 'sig1',
|
||||
}
|
||||
|
||||
expect(compareEvents(event, { ...event, created_at: 1610000000 })).toBeLessThan(0)
|
||||
expect(compareEvents(event, { ...event, id: 'abc124' })).toBeLessThan(0)
|
||||
expect(compareEvents(event, { ...event })).toBe(0)
|
||||
})
|
||||
|
||||
test('sortEvents', () => {
|
||||
const events = [
|
||||
|
||||
@@ -52,16 +52,22 @@ export function validateEvent<T>(event: T): event is T & UnsignedEvent {
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare events in reverse-chronological order by the `created_at` timestamp,
|
||||
* and then by the event `id` (lexicographically) in case of ties.
|
||||
*/
|
||||
export function compareEvents(a: Event, b: Event): number {
|
||||
if (a.created_at !== b.created_at) {
|
||||
return b.created_at - a.created_at
|
||||
}
|
||||
return a.id.localeCompare(b.id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort events in reverse-chronological order by the `created_at` timestamp,
|
||||
* and then by the event `id` (lexicographically) in case of ties.
|
||||
* This mutates the array.
|
||||
*/
|
||||
export function sortEvents(events: Event[]): Event[] {
|
||||
return events.sort((a: NostrEvent, b: NostrEvent): number => {
|
||||
if (a.created_at !== b.created_at) {
|
||||
return b.created_at - a.created_at
|
||||
}
|
||||
return a.id.localeCompare(b.id)
|
||||
})
|
||||
return events.sort(compareEvents)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user