Class: Node

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/usearchtree/node.rb

Overview

Represents to a node in the graph

Author: Johnny Lee Othon

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, name = nil) ⇒ Node

Returns a new instance of Node.



10
11
12
13
14
# File 'lib/usearchtree/node.rb', line 10

def initialize id, name=nil
    @name = name
    @id = id
    @edges = Array.new
end

Instance Attribute Details

#idObject

Returns the value of attribute id.



6
7
8
# File 'lib/usearchtree/node.rb', line 6

def id
  @id
end

#nameObject

Returns the value of attribute name.



6
7
8
# File 'lib/usearchtree/node.rb', line 6

def name
  @name
end

Instance Method Details

#<=>(other) ⇒ Object



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

def <=> other
    return @id <=> other.id
end

#add_edge(node, cost) ⇒ Object



45
46
47
# File 'lib/usearchtree/node.rb', line 45

def add_edge node, cost
    @edges << Edge.new(node, cost)
end

#cost(node) ⇒ Object



49
50
51
52
53
54
# File 'lib/usearchtree/node.rb', line 49

def cost node
    edge = @edges.find{|e| e.node == node}
    if edge
        edge.cost
    end
end

#edgesObject

Gets an enumerator of the edges



62
63
64
# File 'lib/usearchtree/node.rb', line 62

def edges
    return @edges.each
end

#inspectObject

Returns the name of the node or its id as a string.



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

def inspect
    self.to_s
end

#keyObject

Gets the name if exists or the id



57
58
59
# File 'lib/usearchtree/node.rb', line 57

def key
    @name or @id
end

#to_adjacency_listObject

Returns the node in the format <id:name>.



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/usearchtree/node.rb', line 31

def to_adjacency_list
    s = "#{name}"
    unless @name.nil? or @name.empty?
        s += "(#{@id})"
    end
    unless @edges.empty?
        s += ": "
    end
    nodes = @edges.map do |edge|
        "#{edge.node}=>#{edge.cost}"
    end.join(", ")
    s += nodes
end

#to_sObject

Returns the name of the node or its id as a string.



17
18
19
# File 'lib/usearchtree/node.rb', line 17

def to_s
    @name or "#{@id}"
end