()
| 15 | export const defaultScheduler: ScheduleFunction = systemSetTimeoutZero |
| 16 | |
| 17 | export function createNotifyManager() { |
| 18 | let queue: Array<NotifyCallback> = [] |
| 19 | let transactions = 0 |
| 20 | let notifyFn: NotifyFunction = (callback) => { |
| 21 | callback() |
| 22 | } |
| 23 | let batchNotifyFn: BatchNotifyFunction = (callback: () => void) => { |
| 24 | callback() |
| 25 | } |
| 26 | let scheduleFn = defaultScheduler |
| 27 | |
| 28 | const schedule = (callback: NotifyCallback): void => { |
| 29 | if (transactions) { |
| 30 | queue.push(callback) |
| 31 | } else { |
| 32 | scheduleFn(() => { |
| 33 | notifyFn(callback) |
| 34 | }) |
| 35 | } |
| 36 | } |
| 37 | const flush = (): void => { |
| 38 | const originalQueue = queue |
| 39 | queue = [] |
| 40 | if (originalQueue.length) { |
| 41 | scheduleFn(() => { |
| 42 | batchNotifyFn(() => { |
| 43 | originalQueue.forEach((callback) => { |
| 44 | notifyFn(callback) |
| 45 | }) |
| 46 | }) |
| 47 | }) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | return { |
| 52 | batch: <T>(callback: () => T): T => { |
| 53 | let result |
| 54 | transactions++ |
| 55 | try { |
| 56 | result = callback() |
| 57 | } finally { |
| 58 | transactions-- |
| 59 | if (!transactions) { |
| 60 | flush() |
| 61 | } |
| 62 | } |
| 63 | return result |
| 64 | }, |
| 65 | /** |
| 66 | * All calls to the wrapped function will be batched. |
| 67 | */ |
| 68 | batchCalls: <T extends Array<unknown>>( |
| 69 | callback: BatchCallsCallback<T>, |
| 70 | ): BatchCallsCallback<T> => { |
| 71 | return (...args) => { |
| 72 | schedule(() => { |
| 73 | callback(...args) |
| 74 | }) |
no test coverage detected