Class: Pinmark::Tracker

Inherits:
Object
  • Object
show all
Defined in:
lib/pinmark/tracker.rb

Defined Under Namespace

Classes: StackUnderflowError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeTracker

Returns a new instance of Tracker.



10
11
12
13
14
# File 'lib/pinmark/tracker.rb', line 10

def initialize
  @nodes = []
  @stack = []
  @counter = 0
end

Instance Attribute Details

#nodesObject (readonly)

Returns the value of attribute nodes.



8
9
10
# File 'lib/pinmark/tracker.rb', line 8

def nodes
  @nodes
end

Instance Method Details

#popObject



25
26
27
28
29
# File 'lib/pinmark/tracker.rb', line 25

def pop
  raise StackUnderflowError, "pinmark stack underflow" if @stack.empty?

  @stack.pop
end

#push(component:, source:) ⇒ Object



16
17
18
19
20
21
22
23
# File 'lib/pinmark/tracker.rb', line 16

def push(component:, source:)
  @counter += 1
  id = "pm-#{@counter}"
  parent_id = @stack.last
  @nodes << { id:, component:, source:, parent_id: }
  @stack.push(id)
  id
end

#treeObject



31
32
33
34
35
36
37
38
39
# File 'lib/pinmark/tracker.rb', line 31

def tree
  by_parent = @nodes.group_by { |node| node[:parent_id] }
  build = lambda { |parent_id|
    (by_parent[parent_id] || []).map do |node|
      node.merge(children: build.call(node[:id]))
    end
  }
  build.call(nil)
end