idlize

Форк
0
72 строки · 2.0 Кб
1
/*
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
6
 *
7
 * http://www.apache.org/licenses/LICENSE-2.0
8
 *
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.
14
 */
15

16
import { uint32 } from "@koalaui/compat"
17

18
/**
19
 * This class represents a path to a node in a tree.
20
 */
21
export class TreePath<Node> {
22
    readonly node: Node
23
    readonly parent: TreePath<Node> | undefined
24

25
    /**
26
     * Creates a tree path to the given node relative to the specified parent path.
27
     * The path represents a root node if parent path is undefined.
28
     *
29
     * @param node    a node in a tree
30
     * @param parent  a path to a parent node or undefined for the root
31
     */
32
    constructor(node: Node, parent?: TreePath<Node>) {
33
        this.node = node
34
        this.parent = parent
35
    }
36

37
    /**
38
     * Creates a tree path to the specified child node.
39
     *
40
     * @param node  a node in a tree
41
     */
42
    child(node: Node): TreePath<Node> {
43
        return new TreePath<Node>(node, this)
44
    }
45

46
    /**
47
     * Returns the tree path that represents the root node.
48
     * The root path returns itself.
49
     */
50
    get root(): TreePath<Node> {
51
        return this.parent?.root ?? this
52
    }
53

54
    /**
55
     * Returns the depth of the tree path relative to the root node.
56
     * The root path returns 0.
57
     */
58
    get depth(): uint32 {
59
        let count: uint32 = 0
60
        let parent = this.parent
61
        while (parent !== undefined) {
62
            parent = parent!.parent
63
            count++
64
        }
65
        return count
66
    }
67

68
    toString(): string {
69
        let parent = this.parent ?? ""
70
        return `${parent}/${this.node}`
71
    }
72
}
73

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.