All files / src/utils subscription-manager.ts

100% Statements 24/24
100% Branches 6/6
100% Functions 6/6
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 4747x       47x 9168x   1351x 1351x 1351x     47x         7256x   7256x   2300x       2278x   22x         44x 44x         47x 3440x     47x 3653x   47x  
import { addUniqueItem, removeItem } from "./array"
 
type GenericHandler = (...args: any) => void
 
export class SubscriptionManager<Handler extends GenericHandler> {
    private subscriptions: Handler[] = []
 
    add(handler: Handler) {
        addUniqueItem(this.subscriptions, handler)
        return () => removeItem(this.subscriptions, handler)
    }
 
    notify(
        a?: Parameters<Handler>[0],
        b?: Parameters<Handler>[1],
        c?: Parameters<Handler>[2]
    ) {
        const numSubscriptions = this.subscriptions.length
 
        if (!numSubscriptions) return
 
        if (numSubscriptions === 1) {
            /**
             * If there's only a single handler we can just call it without invoking a loop.
             */
            this.subscriptions[0](a, b, c)
        } else {
            for (let i = 0; i < numSubscriptions; i++) {
                /**
                 * Check whether the handler exists before firing as it's possible
                 * the subscriptions were modified during this loop running.
                 */
                const handler = this.subscriptions[i]
                handler && handler(a, b, c)
            }
        }
    }
 
    getSize() {
        return this.subscriptions.length
    }
 
    clear() {
        this.subscriptions.length = 0
    }
}