JavaScript segment tree approach (commented)
\njavascript []\nclass Node {\n    constructor() {\n        this.count = 0;\n        this.left  = null;\n        this.right = null;\n    }\n}\n\nclass CountInte
\n```javascript []\nclass Node {\n    constructor() {\n        this.count = 0;\n        this.left  = null;\n        this.right = null;\n    }\n}\n\nclass CountIntervals {\n    constructor() {\n        this.root = new Node();\n    }\n\n    add(left, right) {\n        this.#addInterval(this.root, 1, 10**9, left, right);\n    }\n\n    #addInterval(node, l, r, intervalLeft, intervalRight) {\n        // outside interval. Exit function\n        if (l > intervalRight || r < intervalLeft) {\n            return node;\n        }\n\n        // need new node for interval\n        if (node == null) {\n            node = new Node();\n        }\n\n        // no new integers to add within [intervalLeft, intervalRight]\n        if (node.count === r - l + 1) {\n            return node;\n        }\n\n        // node interval within [intervalLeft, intervalRight]\n        // update node.count to reflect this\n        if (intervalLeft <= l && intervalRight >= r) {\n            node.count = r - l + 1;\n            return node;\n        }\n\n        // need to continue binary search\n        let mid = (l + r) >> 1;\n        node.left  = this.#addInterval(node.left, l, mid, intervalLeft, intervalRight);\n        node.right = this.#addInterval(node.right, mid+1, r, intervalLeft, intervalRight);\n\n        node.count = 0;\n        node.count += node.left  ? node.left.count  : 0;\n        node.count += node.right ? node.right.count : 0;\n        return node;\n    }\n\n    count() {\n        return this.root.count;\n    }\n}\n```
['JavaScript']