1+ using System . Collections . Generic ;
2+
3+ // ReSharper disable ForCanBeConvertedToForeach
4+
5+ namespace Platform . Collections . Trees
6+ {
7+ public class Node
8+ {
9+ private Dictionary < object , Node > _childNodes ;
10+
11+ public object Value { get ; set ; }
12+
13+ public Dictionary < object , Node > ChildNodes => _childNodes ?? ( _childNodes = new Dictionary < object , Node > ( ) ) ;
14+
15+ public Node this [ object key ]
16+ {
17+ get
18+ {
19+ var child = GetChild ( key ) ;
20+ if ( child == null )
21+ child = AddChild ( key ) ;
22+ return child ;
23+ }
24+ set => SetChildValue ( value , key ) ;
25+ }
26+
27+ public Node ( object value ) => Value = value ;
28+
29+ public Node ( )
30+ : this ( null )
31+ {
32+ }
33+
34+ public bool ContainsChild ( params object [ ] keys ) => GetChild ( keys ) != null ;
35+
36+ public Node GetChild ( params object [ ] keys )
37+ {
38+ var node = this ;
39+ for ( var i = 0 ; i < keys . Length ; i ++ )
40+ {
41+ node . ChildNodes . TryGetValue ( keys [ i ] , out node ) ;
42+ if ( node == null )
43+ return null ;
44+ }
45+
46+ return node ;
47+ }
48+
49+ public object GetChildValue ( params object [ ] keys ) => GetChild ( keys ) ? . Value ;
50+
51+ public Node AddChild ( object key ) => AddChild ( key , new Node ( null ) ) ;
52+
53+ public Node AddChild ( object key , object value ) => AddChild ( key , new Node ( value ) ) ;
54+
55+ public Node AddChild ( object key , Node child )
56+ {
57+ ChildNodes . Add ( key , child ) ;
58+ return child ;
59+ }
60+
61+ public Node SetChild ( params object [ ] keys ) => SetChildValue ( null , keys ) ;
62+
63+ public Node SetChild ( object key ) => SetChildValue ( null , key ) ;
64+
65+ public Node SetChildValue ( object value , params object [ ] keys )
66+ {
67+ var node = this ;
68+ for ( var i = 0 ; i < keys . Length ; i ++ )
69+ node = SetChildValue ( value , keys [ i ] ) ;
70+ node . Value = value ;
71+ return node ;
72+ }
73+
74+ public Node SetChildValue ( object value , object key )
75+ {
76+ if ( ! ChildNodes . TryGetValue ( key , out Node child ) )
77+ child = AddChild ( key , value ) ;
78+ child . Value = value ;
79+ return child ;
80+ }
81+ }
82+ }
0 commit comments