mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2025-12-09 16:48:50 +00:00
Add stable sortEvents function
This commit is contained in:
19
core.test.ts
Normal file
19
core.test.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { test, expect } from 'bun:test'
|
||||||
|
|
||||||
|
import { sortEvents } from './core.ts'
|
||||||
|
|
||||||
|
test('sortEvents', () => {
|
||||||
|
const events = [
|
||||||
|
{ id: 'abc123', pubkey: 'key1', created_at: 1610000000, kind: 1, tags: [], content: 'Hello', sig: 'sig1' },
|
||||||
|
{ id: 'abc124', pubkey: 'key2', created_at: 1620000000, kind: 1, tags: [], content: 'World', sig: 'sig2' },
|
||||||
|
{ id: 'abc125', pubkey: 'key3', created_at: 1620000000, kind: 1, tags: [], content: '!', sig: 'sig3' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const sortedEvents = sortEvents(events)
|
||||||
|
|
||||||
|
expect(sortedEvents).toEqual([
|
||||||
|
{ id: 'abc124', pubkey: 'key2', created_at: 1620000000, kind: 1, tags: [], content: 'World', sig: 'sig2' },
|
||||||
|
{ id: 'abc125', pubkey: 'key3', created_at: 1620000000, kind: 1, tags: [], content: '!', sig: 'sig3' },
|
||||||
|
{ id: 'abc123', pubkey: 'key1', created_at: 1610000000, kind: 1, tags: [], content: 'Hello', sig: 'sig1' },
|
||||||
|
])
|
||||||
|
})
|
||||||
14
core.ts
14
core.ts
@@ -49,3 +49,17 @@ export function validateEvent<T>(event: T): event is T & UnsignedEvent {
|
|||||||
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user