feat: 💨

This commit is contained in:
codytseng 2026-01-02 02:40:13 +08:00
parent fd9f41c8f4
commit 167b6627f1
5 changed files with 124 additions and 72 deletions

47
src/lib/timeline.ts Normal file
View file

@ -0,0 +1,47 @@
import { NostrEvent } from 'nostr-tools'
import { compareEvents } from './event'
export function mergeTimelines(timelines: NostrEvent[][], limit: number) {
if (timelines.length === 0) return []
if (timelines.length === 1) return [...timelines[0]]
return timelines.reduce((merged, current) => _mergeTimelines(merged, current, limit), [])
}
function _mergeTimelines(a: NostrEvent[], b: NostrEvent[], limit: number): NostrEvent[] {
if (a.length === 0) return [...b]
if (b.length === 0) return [...a]
const result: NostrEvent[] = []
let i = 0
let j = 0
while (i < a.length && j < b.length) {
const cmp = compareEvents(a[i], b[j])
if (cmp > 0) {
result.push(a[i])
i++
} else if (cmp < 0) {
result.push(b[j])
j++
} else {
result.push(a[i])
i++
j++
}
}
if (result.length >= limit) {
return result
}
while (i < a.length && result.length < limit) {
result.push(a[i])
i++
}
while (j < b.length && result.length < limit) {
result.push(b[j])
j++
}
return result
}