mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2026-10-05 14:38:23 +00:00
export event comparator.
This commit is contained in:
+17
-1
@@ -1,5 +1,21 @@
|
|||||||
import { test, expect } from 'bun:test'
|
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', () => {
|
test('sortEvents', () => {
|
||||||
const events = [
|
const events = [
|
||||||
|
|||||||
@@ -52,16 +52,22 @@ export function validateEvent<T>(event: T): event is T & UnsignedEvent {
|
|||||||
return true
|
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,
|
* Sort events in reverse-chronological order by the `created_at` timestamp,
|
||||||
* and then by the event `id` (lexicographically) in case of ties.
|
* and then by the event `id` (lexicographically) in case of ties.
|
||||||
* This mutates the array.
|
* This mutates the array.
|
||||||
*/
|
*/
|
||||||
export function sortEvents(events: Event[]): Event[] {
|
export function sortEvents(events: Event[]): Event[] {
|
||||||
return events.sort((a: NostrEvent, b: NostrEvent): number => {
|
return events.sort(compareEvents)
|
||||||
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