Class: CompSci::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/compsci/node.rb

Overview

has a value and an array of children; allows child gaps

Direct Known Subclasses

ChildNode, FlexNode, KeyNode

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, children: 2, metadata: {}) ⇒ Node

Returns a new instance of Node.



16
17
18
19
20
# File 'lib/compsci/node.rb', line 16

def initialize(value, children: 2, metadata: {})
  @value = value
  @children = Array.new(children)
  @metadata = 
end

Instance Attribute Details

#childrenObject (readonly)

Returns the value of attribute children.



14
15
16
# File 'lib/compsci/node.rb', line 14

def children
  @children
end

#metadataObject

Returns the value of attribute metadata.



13
14
15
# File 'lib/compsci/node.rb', line 13

def 
  @metadata
end

#valueObject

Returns the value of attribute value.



13
14
15
# File 'lib/compsci/node.rb', line 13

def value
  @value
end

Class Method Details

.display_line(nodes: [], width: 80) ⇒ Object



4
5
6
7
8
9
10
11
# File 'lib/compsci/node.rb', line 4

def self.display_line(nodes: [], width: 80)
  block_width = [width / nodes.size, 1].max
  nodes.map { |node|
    str = node ? node.to_s : '_'
    space = [(block_width + str.size) / 2, str.size + 1].max
    str.ljust(space, ' ').rjust(block_width, ' ')
  }.join
end

Instance Method Details

#[](idx) ⇒ Object



22
23
24
# File 'lib/compsci/node.rb', line 22

def [](idx)
  @children[idx]
end

#[]=(idx, node) ⇒ Object



26
27
28
# File 'lib/compsci/node.rb', line 26

def []=(idx, node)
  @children[idx] = node
end

#display(width: 80) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/compsci/node.rb', line 39

def display(width: 80)
  lines = [self.class.display_line(nodes: [self], width: width)]
  nodes = @children
  while nodes.any? { |n| !n.nil? }
    lines << self.class.display_line(nodes: nodes, width: width)
    if nodes.size > 3**7
      lines << "nodes.size = #{nodes.size}; abort render"
      break
    end
    nodes = nodes.reduce([]) { |memo, n|
      memo + Array.new(@children.size) { |i| n and n.children[i] }
    }
  end
  lines.join("\n")
end

#inspectObject



34
35
36
37
# File 'lib/compsci/node.rb', line 34

def inspect
  "#<%s:0x%0xi @value=%s @children=[%s]>" %
    [self.class, self.object_id, self, @children.join(', ')]
end

#to_sObject



30
31
32
# File 'lib/compsci/node.rb', line 30

def to_s
  @value.to_s
end