(items: T[], predicate: (item: T) => boolean, synthesize: (batch: T[]) => T)
| 7 | * - Non-matching items are preserved in-order. |
| 8 | */ |
| 9 | export function batchConsecutive<T>(items: T[], predicate: (item: T) => boolean, synthesize: (batch: T[]) => T): T[] { |
| 10 | const result: T[] = [] |
| 11 | let i = 0 |
| 12 | |
| 13 | while (i < items.length) { |
| 14 | if (predicate(items[i])) { |
| 15 | // Collect consecutive matches into a batch |
| 16 | const batch: T[] = [items[i]] |
| 17 | let j = i + 1 |
| 18 | |
| 19 | while (j < items.length && predicate(items[j])) { |
| 20 | batch.push(items[j]) |
| 21 | j++ |
| 22 | } |
| 23 | |
| 24 | if (batch.length > 1) { |
| 25 | result.push(synthesize(batch)) |
| 26 | } else { |
| 27 | result.push(batch[0]) |
| 28 | } |
| 29 | |
| 30 | i = j |
| 31 | } else { |
| 32 | result.push(items[i]) |
| 33 | i++ |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | return result |
| 38 | } |
no outgoing calls
no test coverage detected