diff --git a/lib/visual_graphs/graph.rb b/lib/visual_graphs/graph.rb index 1f7ca6e..08411d1 100644 --- a/lib/visual_graphs/graph.rb +++ b/lib/visual_graphs/graph.rb @@ -79,6 +79,27 @@ def dump_to_json(path) File.open(path, 'w') { |f| f.write(@adjacency_list.to_json) } end + + def each(&block) + if block_given? + @edges.each { |e| yield e} + self + else + @edges.to_enum + end + end + + def each_with_index(&block) + if block_given? + @edges.each_with_index { |e, i| yield(e, i) } + self + else + @edges.to_enum + end + end + + + # convert adjacency list based graph to adjacency matrix based graph # return adjacency matrix based graph def to_adj_matrix_graph @@ -95,4 +116,5 @@ def to_adj_matrix_graph end end + end \ No newline at end of file diff --git a/test/adjacency_list_graph_test.rb b/test/adjacency_list_graph_test.rb index 3cf57a9..51243cb 100644 --- a/test/adjacency_list_graph_test.rb +++ b/test/adjacency_list_graph_test.rb @@ -96,4 +96,42 @@ def test_loop_edge_will_not_add_same_vertex_twice assert_equal 1, graph.vertices.count(4), 'more than 1 vertex was added during looped-edge inserting' end + def test_each_for_edges_array + graph = Graph.load_from_json(@filepath) + test_arr=[] + graph.each { |x| test_arr.append(x) } + assert_equal [[1,2], [2, 3], [3, 1]], test_arr + test_arr.clear + graph.insert_edge([1,4]) + graph.each { |x| test_arr.append(x) } + assert_equal [[1,2], [2, 3], [3, 1],[1, 4]], test_arr + test_arr.clear + graph.insert_edge([3,2]) + graph.each { |x| test_arr.append(x) } + assert_equal [[1,2], [2, 3], [3, 1],[1, 4], [3, 2]],test_arr + end + + def test_each_with_index_for_edges_array + graph = Graph.load_from_json(@filepath) + test_arr=[] + graph.each_with_index{ |x, i| test_arr.append(x, i)} + assert_equal [[1, 2], 0, [2, 3], 1, [3, 1], 2],test_arr + test_arr.clear + graph.insert_edge([4, 4]) + graph.each_with_index { |x,i| test_arr.append(x, i)} + assert_equal [[1, 2], 0, [2, 3], 1, [3, 1], 2, [4, 4], 3], test_arr + test_arr.clear + graph.insert_edge([1,4]) + graph.insert_edge([2,5]) + graph.each_with_index { |x, i| test_arr.append(x, i)} + assert_equal [[1, 2], 0, [2, 3], 1, [3, 1], 2, [4, 4], 3, [1, 4], 4, [2, 5], 5], test_arr + test_arr.clear + graph.insert_edge([3,5]) + graph.each_with_index { |x, i| test_arr.append(x, i)} + assert_equal [[1, 2], 0, [2, 3], 1, [3, 1], 2, [4, 4], 3, [1, 4], 4, [2, 5], 5, [3, 5], 6], test_arr + + + + end + end