* O(n) single-pass: find the message with the latest timestamp matching a predicate. * Replaces the `[...values].filter(pred).sort((a,b) => Date(b)-Date(a))[0]` pattern * which is O(n log n) + 2n Date allocations.
( messages: Iterable<T>, predicate: (m: T) => boolean, )
| 2044 | * which is O(n log n) + 2n Date allocations. |
| 2045 | */ |
| 2046 | function findLatestMessage<T extends { timestamp: string }>( |
| 2047 | messages: Iterable<T>, |
| 2048 | predicate: (m: T) => boolean, |
| 2049 | ): T | undefined { |
| 2050 | let latest: T | undefined |
| 2051 | let maxTime = -Infinity |
| 2052 | for (const m of messages) { |
| 2053 | if (!predicate(m)) continue |
| 2054 | const t = Date.parse(m.timestamp) |
| 2055 | if (t > maxTime) { |
| 2056 | maxTime = t |
| 2057 | latest = m |
| 2058 | } |
| 2059 | } |
| 2060 | return latest |
| 2061 | } |
| 2062 | |
| 2063 | /** |
| 2064 | * Builds a conversation chain from a leaf message to root |
no test coverage detected