lib/nanoc/base/directed_graph.rb in nanoc-3.3.2 vs lib/nanoc/base/directed_graph.rb in nanoc-3.3.3
- old
+ new
@@ -29,31 +29,24 @@
# # => %w( c )
# graph.predecessors_of('d').sort
# # => %w( b c )
class DirectedGraph
- # The set of vertices in this graph.
- #
- # @return [Set]
- attr_reader :vertices
-
# @group Creating a graph
# Creates a new directed graph with the given vertices.
def initialize(vertices)
- @vertices = Set.new(vertices)
+ @vertices = {}
+ vertices.each_with_index do |v,i|
+ @vertices[v] = i
+ end
@from_graph = {}
@to_graph = {}
- @vertice_indexes = {}
- @vertices.each_with_index do |v, i|
- @vertice_indexes[v] = i
- end
+ @roots = Set.new(@vertices.keys)
- @roots = Set.new(@vertices)
-
invalidate_caches
end
# @group Modifying the graph
@@ -70,11 +63,11 @@
@from_graph[from] ||= Set.new
@from_graph[from] << to
@to_graph[to] ||= Set.new
- @to_graph[to] << from
+ @to_graph[to] << from
@roots.delete(to)
invalidate_caches
end
@@ -107,16 +100,15 @@
#
# @return [void]
#
# @since 3.2.0
def add_vertex(v)
- return if @vertices.include?(v)
+ return if @vertices.has_key?(v)
- @vertices << v
- @vertice_indexes[v] = @vertices.size-1
+ @vertices[v] = @vertices.size
- @roots << v
+ @roots << v
end
# Deletes all edges coming from the given vertex.
#
# @param from Vertex from which all edges should be removed
@@ -204,18 +196,23 @@
# @return [Array] Successors of the given vertex
def successors_of(from)
@successors[from] ||= recursively_find_vertices(from, :direct_successors_of)
end
+ # @return [Array] The list of all vertices in this graph.
+ def vertices
+ @vertices.keys.sort_by { |v| @vertices[v] }
+ end
+
# Returns an array of tuples representing the edges. The result of this
# method may take a while to compute and should be cached if possible.
#
# @return [Array] The list of all edges in this graph.
def edges
result = []
- @vertices.each_with_index do |v, i|
- direct_successors_of(v).map { |v2| @vertice_indexes[v2] }.each do |i2|
- result << [ i, i2 ]
+ @vertices.each_pair do |v1, i1|
+ direct_successors_of(v1).map { |v2| @vertices[v2] }.each do |i2|
+ result << [ i1, i2 ]
end
end
result
end