End of the day
[graph.njae.git] / lib / graph.njae / edge.rb
1 require 'ostruct'
2
3 # A simple graph library
4
5 module GraphNjae
6
7 # An edge (or multiedge) in a graph. The edge can have arbitrary attributes,
8 # treated as method names.
9 #
10 # Each connection is handled by a Graph::Connection object, so that each end
11 # of the Edge can have it's own attributes.
12 class Edge < OpenStruct
13 def initialize(values = {})
14 super(values)
15 self.connections = []
16 self
17 end
18
19 # Connect this edge to a vertex
20 def <<(other)
21 c = Connection.new
22 c.end = other
23 other.edges << self unless other.edges.include? self
24 self.connections << c
25 self
26 end
27
28 # Return the set of vertices this edge connects.
29 def vertices
30 self.connections.map {|c| c.end}
31 end
32
33 # Return the connection object that joins this Edge to the specified Vertex
34 def connection_at(vertex)
35 self.connections.find {|c| c.end.equal? vertex}
36 end
37
38 # Return the vertex at the other end of the one given.
39 # Self-loops should still return the vertex
40 def other_end(vertex)
41 if self.vertices[0] == vertex
42 self.vertices[1]
43 else
44 self.vertices[0]
45 end
46 end
47
48 def to_s
49 '<E: ' + self.type.to_s + ' [' + self.vertices.map {|n| n.to_s}.join(', ') + '] >'
50 end
51 end
52
53 # A connection between an Edge and a Vertex.The connection can have arbitrary attributes,
54 # treated as method names.
55 class Connection < OpenStruct
56 def initialize(values = {})
57 super(values)
58 self
59 end
60 end
61 end