2
* Copyright (c) 2022-2023 Huawei Device Co., Ltd.
3
* Licensed under the Apache License, Version 2.0 (the "License");
4
* you may not use this file except in compliance with the License.
5
* You may obtain a copy of the License at
7
* http://www.apache.org/licenses/LICENSE-2.0
9
* Unless required by applicable law or agreed to in writing, software
10
* distributed under the License is distributed on an "AS IS" BASIS,
11
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
* See the License for the specific language governing permissions and
13
* limitations under the License.
16
import { int32, uint32 } from "@koalaui/compat"
17
import { TreePath } from "./TreePath"
20
* This class provides basic functionality for tree building or incremental tree updating.
22
export abstract class TreeUpdater<Node> {
23
private current: TreePath<Node>
24
readonly reverse: boolean
27
* @param root the tree root that always exists
28
* @param reverse `false` builds a tree top-down, `true` build a tree bottom-up
30
constructor(root: Node, reverse: boolean = false) {
31
this.current = new TreePath<Node>(root)
32
this.reverse = reverse
36
* Returns the path to the selected node.
38
get path(): TreePath<Node> {
43
* Returns the selected node to perform tree change operations.
46
return this.current.node
50
* Selects the specified child node when the updater is getting traversed down the tree.
52
down(node: Node): void {
53
this.current = this.current.child(node)
57
* Selects the parent node when the updater is getting traversed up the tree.
60
let parent = this.current.parent
61
if (parent === undefined) throw new Error("unexpected")
66
* Selects the root node to prepare the updater to traversing a tree.
69
this.current = this.current.root
73
* Inserts the specified node as a child of a selected node at the given index.
75
abstract insert(index: int32, node: Node): void
78
* Removes the specified amount of children from the given index.
80
abstract remove(index: int32, amount: uint32): void
83
* Moves the specified amount of children from the indexFrom to the indexTo.
85
abstract move(indexFrom: int32, indexTo: int32, amount: uint32): void