MediumTypeScript

Composite

TypeScriptDesign PatternsStructuralComposite

Treat individual objects and compositions of objects uniformly — a file and a folder full of files should answer getSize() the same way, recursively.

Implement `FileNode.getSize()` (returns its own size) and FolderNode.getSize()/add() (sums its children's sizes, recursively).

solve(tree) builds a tree from nested numbers/arrays (5 = a file of size 5, [a, b] = a folder containing a and b) and returns the total size.

solve([1, [2, 3], [4, [5, 6]]])21

Sample tests

Test #1Flat folder of files
Input: [[1,2,3]]
Output: 6
Test #2Nested folders
Input: [[1,[2,3],[4,[5,6]]]]
Output: 21
Test #3Empty folder
Input: [[]]
Output: 0