Module: BEL::LibBEL::NodeTraversal

Includes:
Enumerable
Defined in:
lib/bel/libbel/node_traversal.rb

Instance Method Summary collapse

Instance Method Details

#each(traversal = :depth_first, callable = nil, &block) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/bel/libbel/node_traversal.rb', line 6

def each(traversal = :depth_first, callable = nil, &block)
  func = if block_given?
           block
         else
           callable
         end
  if !func
    if traversal == :depth_first
      enum_for(:each_depth_first)
    elsif traversal == :breadth_first
      enum_for(:each_breadth_first)
    end
  else
    if traversal == :depth_first
      each_depth_first(callable, &block)
    elsif traversal == :breadth_first
      each_breadth_first(callable, &block)
    end
  end
end

#each_breadth_first(callable = nil, queue = [], &block) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/bel/libbel/node_traversal.rb', line 57

def each_breadth_first(callable = nil, queue = [], &block)
  func = if block_given?
           block
         else
           callable
         end
  if !func
    enum_for(:each_breadth_first)
  else
    typed_node = (queue.shift || self).to_typed_node
    func.call(typed_node)

    if typed_node.is_a? (LibBEL::BelAstNodeToken)
      if !typed_node.left.pointer.null?
        queue << typed_node.left
      end
      if func.respond_to?(:between)
        func.between(typed_node)
      end
      if !typed_node.right.pointer.null?
        queue << typed_node.right
      end
    end

    if func.respond_to?(:after)
      func.after(typed_node)
    end

    if !queue.empty?
      queue.first.each_breadth_first(queue, &block)
    end
  end
end

#each_depth_first(callable = nil, &block) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/bel/libbel/node_traversal.rb', line 27

def each_depth_first(callable = nil, &block)
  func = if block_given?
           block
         else
           callable
         end
  if !func
    enum_for(:each_depth_first)
  else
    typed_node = self.to_typed_node
    func.call(typed_node)

    if typed_node.is_a? (LibBEL::BelAstNodeToken)
      if !typed_node.left.pointer.null?
        typed_node.left.each_depth_first(func)
      end
      if func.respond_to?(:between)
        func.between(typed_node)
      end
      if !typed_node.right.pointer.null?
        typed_node.right.each_depth_first(func)
      end
    end

    if func.respond_to?(:after)
      func.after(typed_node)
    end
  end
end

#traversal_method(obj, traversal) ⇒ Object



91
92
93
94
95
96
97
# File 'lib/bel/libbel/node_traversal.rb', line 91

def traversal_method(obj, traversal)
  if traversal == :breadth_first
    obj.method(:each_breadth_first)
  else
    obj.method(:each_depth_first)
  end
end