* 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, )
| 2081 | * which is O(n log n) + 2n Date allocations. |
| 2082 | */ |
| 2083 | function findLatestMessage<T extends { timestamp: string }>( |
| 2084 | messages: Iterable<T>, |
| 2085 | predicate: (m: T) => boolean, |
| 2086 | ): T | undefined { |
| 2087 | let latest: T | undefined |
| 2088 | let maxTime = -Infinity |
| 2089 | for (const m of messages) { |
| 2090 | if (!predicate(m)) continue |
| 2091 | const t = Date.parse(m.timestamp) |
| 2092 | if (t > maxTime) { |
| 2093 | maxTime = t |
| 2094 | latest = m |
| 2095 | } |
| 2096 | } |
| 2097 | return latest |
| 2098 | } |
| 2099 | |
| 2100 | /** |
| 2101 | * Builds a conversation chain from a leaf message to root |
no outgoing calls
no test coverage detected