35e913d1670e130a44bacfe6ea53ee3eb00e972d
[vid.git] / vid-app-common / src / main / java / org / onap / vid / utils / Tree.kt
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.vid.utils
22
23 data class Node<T>(val value:T, val children:MutableMap<T, Node<T>> = hashMapOf())
24
25 data class Tree<T>(private val root:Node<T>) {
26
27     constructor(value: T) : this(Node(value))
28
29     fun getRootValue():T {
30         return root.value;
31     }
32
33     fun addPath(vararg path: T) {
34         addPath(path.asList())
35     }
36
37     fun addPath(path:Collection<T>) {
38         var currentNode = root
39         path.forEach {
40             currentNode = currentNode.children.getOrPut(it) {Node(it)}
41         }
42     }
43
44     fun getSubTree(vararg path: T): Tree<T>? {
45         return getSubTree(path.asList())
46     }
47
48     fun getSubTree(path:Collection<T>): Tree<T>? {
49         var currentNode:Node<T> = root
50         path.forEach {
51             currentNode = currentNode.children[it] ?: return null
52         }
53         return Tree(currentNode)
54     }
55
56     fun isPathExist(vararg path: T): Boolean {
57         return isPathExist(path.asList())
58     }
59
60     fun isPathExist(path:Collection<T>): Boolean {
61         return getSubTree(path)!=null
62     }
63 }
64