Composite Pattern Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Composite Pattern runs in O(n) time and O(n) space, in JavaScript as in every other language.
- ✓Plain objects with a children array plus recursion, or a generator function using yield* for delegation.
- ✓Write traversal as a generator with yield* so consumers can use for-of, take, and early return without the callback-per-node style forcing an exception to break out.
- ✓The JavaScript trap: JavaScript has no tail-call elimination in practice: proper tail calls are in the ES2015 specification but V8, SpiderMonkey and Chakra all declined to ship them and only JavaScriptCore implemented them, so on Node and Chrome a deep recursion overflows at roughly ten thousand frames with a RangeError that names the wrong function.
- ✓Nested generators delegate through yield* efficiently, but nesting plain iterators by hand and forwarding each next call costs one frame per level per item, which is the quadratic trap.
What Composite Pattern actually is
Composite Pattern in JavaScript: what you actually reach for
JavaScript implementation
function* walk(node) {
yield node;
for (const child of node.children) yield* walk(child); // delegates, not re-wraps
}
// Deep or user-supplied trees: explicit stack. No TCO exists in V8.
function total(root) {
const stack = [root];
let acc = 0;
while (stack.length) {
const n = stack.pop();
acc += n.size ?? 0;
// Do NOT use stack.push(...n.children): spreading throws RangeError
// once a node has ~100k children.
for (const c of n.children) stack.push(c);
}
return acc;
}
const tree = { size: 1, children: [{ size: 2, children: [] }] };
total(tree); // 3
[...walk(tree)].length; // 2Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Composite Pattern?
Plain objects with a children array plus recursion, or a generator function using yield* for delegation. structuredClone copies a whole tree including cycles, which matters once nodes carry parent pointers. Node exposes fs.readdir with the recursive option and the web platform exposes TreeWalker and NodeIterator for DOM composites, both of which are iterative for the same stack reason. Array.prototype.flat(Infinity) flattens nested arrays, which is the composite traversal for the array case.
What is the most common JavaScript mistake when implementing Composite Pattern?
JavaScript has no tail-call elimination in practice: proper tail calls are in the ES2015 specification but V8, SpiderMonkey and Chakra all declined to ship them and only JavaScriptCore implemented them, so on Node and Chrome a deep recursion overflows at roughly ten thousand frames with a RangeError that names the wrong function. Worse, the limit depends on frame size, so the same tree crashes in one build and not another. A recursive tree walk over untrusted or user-generated depth is therefore a denial-of-service vector, not merely a robustness concern.
How does Composite Pattern actually perform in JavaScript?
Nested generators delegate through yield* efficiently, but nesting plain iterators by hand and forwarding each next call costs one frame per level per item, which is the quadratic trap. An explicit stack allocates one array and no frames and is generally the fastest option for large trees. Note that pushing children with stack.push(...node.children) spreads through the argument list and throws a RangeError once a node has roughly a hundred thousand children; a loop or concat avoids that hard limit. Time complexity is O(n) and space is O(n).
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.