File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -39,4 +39,16 @@ function Graph:add_vertex(vertex)
39
39
return false
40
40
end
41
41
42
+ function Graph :add_edge (edge )
43
+ if type (edge ) ~= ' table' then return false end
44
+
45
+ if self ._graph [edge [1 ]] == nil then
46
+ self ._graph [edge [1 ]] = {edge [2 ]}
47
+ else
48
+ table.insert (self ._graph [edge [1 ]], edge [2 ])
49
+ end
50
+
51
+ return true
52
+ end
53
+
42
54
return Graph
Original file line number Diff line number Diff line change @@ -62,3 +62,30 @@ test('should not add vertex', function()
62
62
assert_equal (graph :add_vertex (' b' ), false )
63
63
assert_equal (# graph :get_vertices (), 2 )
64
64
end )
65
+
66
+ test (' should not add edge' , function ()
67
+ local graph = Graph :new ({})
68
+
69
+ assert_equal (graph :add_edge (' a' ), false )
70
+ assert_equal (# graph :get_vertices (), 0 )
71
+ end )
72
+
73
+ test (' add edge in a new vertex' , function ()
74
+ local graph = Graph :new ({})
75
+
76
+ assert_equal (graph :add_edge ({' a' , ' b' }), true )
77
+ assert_equal (# graph :get_vertices (), 1 )
78
+
79
+ local edge = graph :get_edges ()
80
+ assert_equal (edge [1 ][1 ], ' a' )
81
+ assert_equal (edge [1 ][2 ], ' b' )
82
+ end )
83
+
84
+ test (' add edge in a old vertex' , function ()
85
+ local graph = Graph :new ({
86
+ [' a' ] = {' b' }
87
+ })
88
+
89
+ assert_equal (graph :add_edge ({' a' , ' c' }), true )
90
+ assert_equal (# graph :get_vertices (), 1 )
91
+ end )
You can’t perform that action at this time.
0 commit comments