1/* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17export abstract class TreeBuilder<T, U> { 18 protected id: string | undefined; 19 protected name: string | undefined; 20 protected children: U[] = []; 21 22 setName(value: string): this { 23 this.name = value; 24 return this; 25 } 26 27 setChildren(value: U[]): this { 28 this.children = value; 29 return this; 30 } 31 32 build(): T { 33 if (this.id === undefined) { 34 throw Error('id not set'); 35 } 36 if (this.name === undefined) { 37 throw Error('name not set'); 38 } 39 40 const rootNode = this.makeRootNode(); 41 42 this.children.forEach((child) => 43 this.addOrReplaceChildNode(rootNode, child), 44 ); 45 46 return rootNode; 47 } 48 49 protected abstract makeRootNode(): T; 50 protected abstract addOrReplaceChildNode(rootNode: T, child: U): void; 51} 52