Class: InteractorsMindmap::TreeNode

Inherits:
Object
  • Object
show all
Defined in:
lib/interactors_mindmap/tree_node.rb

Overview

Tree node data structure to manage data

Defined Under Namespace

Classes: Node

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root_data:) ⇒ TreeNode

Returns a new instance of TreeNode.



9
10
11
# File 'lib/interactors_mindmap/tree_node.rb', line 9

def initialize(root_data:)
  @root = TreeNode::Node.new(data: root_data)
end

Instance Attribute Details

#rootObject (readonly)

Returns the value of attribute root.



7
8
9
# File 'lib/interactors_mindmap/tree_node.rb', line 7

def root
  @root
end

Instance Method Details

#add_child(child_data:, parent: nil) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/interactors_mindmap/tree_node.rb', line 13

def add_child(child_data:, parent: nil)
  if parent.nil?
    root.add_child(child_data: child_data)
  else
    parent.add_child(child_data: child_data)
  end
end

#add_node_child(node:, parent: nil) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/interactors_mindmap/tree_node.rb', line 21

def add_node_child(node:, parent: nil)
  if parent.nil?
    root.add_node_child(node: node)
  else
    parent.add_node_child(node: node)
  end
end

#reorder_with_recursion!Object



33
34
35
36
37
38
39
# File 'lib/interactors_mindmap/tree_node.rb', line 33

def reorder_with_recursion!
  root.children.each do |child|
    found_nodes = search_node(data: child.data)
    found_children_nodes = found_nodes.select { |node| node.level > child.level }
    found_children_nodes.map { |child_node| child_node.replace_with(node: child) }
  end
end

#search_node(data:) ⇒ Object



29
30
31
# File 'lib/interactors_mindmap/tree_node.rb', line 29

def search_node(data:)
  root.search_node(data: data)
end

#to_formatted_array(node: root) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/interactors_mindmap/tree_node.rb', line 41

def to_formatted_array(node: root)
  array = []

  array << node.formatted_data

  if node.children.any?
    node.children.each do |child|
      array << to_formatted_array(node: child)
    end
  end

  array.flatten
end