* 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, )
| 2202 | * which is O(n log n) + 2n Date allocations. |
| 2203 | */ |
| 2204 | function findLatestMessage<T extends { timestamp: string }>( |
| 2205 | messages: Iterable<T>, |
| 2206 | predicate: (m: T) => boolean, |
| 2207 | ): T | undefined { |
| 2208 | let latest: T | undefined |
| 2209 | let maxTime = -Infinity |
| 2210 | for (const m of messages) { |
| 2211 | if (!predicate(m)) continue |
| 2212 | const t = Date.parse(m.timestamp) |
| 2213 | if (t > maxTime) { |
| 2214 | maxTime = t |
| 2215 | latest = m |
| 2216 | } |
| 2217 | } |
| 2218 | return latest |
| 2219 | } |
| 2220 | |
| 2221 | /** |
| 2222 | * Builds a conversation chain from a leaf message to root |
no outgoing calls
no test coverage detected