File tree Expand file tree Collapse file tree 2 files changed +55
-5
lines changed
lib/data-structures/graphs Expand file tree Collapse file tree 2 files changed +55
-5
lines changed Original file line number Diff line number Diff line change @@ -2,13 +2,42 @@ const Node = require('./node');
22
33/**
44 * Graph that uses an adjacent list
5+ *
6+ * Most common operations:
7+ * - Add vertex
8+ * - Add edge
9+ * - Remove vertex
10+ * - Remove edge
11+ * - Query (query if two vertices are connected)
12+ *
13+ * - Graph search (BFS, DFS)
14+ *
15+ * - Find path (between two vertices)
16+ * - Find all paths (between two vertices)
17+ * - Find shortest paths (between two vertices)
518 */
619class Graph {
7- constructor ( ) {
20+ constructor ( edgeDirection = Graph . DIRECTED ) {
821 this . nodes = new Map ( ) ;
22+ this . edgeDirection = edgeDirection ;
923 }
1024
11- addVertex ( ) {
25+ addVertex ( value ) {
26+ if ( this . nodes . has ( value ) ) {
27+ return this . nodes . get ( value ) ;
28+ } else {
29+ const vertex = new Node ( value ) ;
30+ this . nodes . set ( value , vertex ) ;
31+ return vertex ;
32+ }
33+ }
1234
35+ removeVertex ( value ) {
36+ return this . nodes . delete ( value ) ;
1337 }
14- }
38+ }
39+
40+ Graph . UNDIRECTED = Symbol ( 'directed graph' ) ; // one-way edges
41+ Graph . DIRECTED = Symbol ( 'undirected graph' ) ; // two-ways edges
42+
43+ module . exports = Graph ;
Original file line number Diff line number Diff line change @@ -7,9 +7,30 @@ describe('Graph', () => {
77 graph = new Graph ( ) ;
88 } ) ;
99
10- xdescribe ( '#addVertex' , ( ) => {
10+ describe ( '#addVertex' , ( ) => {
1111 it ( 'should add vertex to graph' , ( ) => {
12- graph . addVertex ( )
12+ const node = graph . addVertex ( 'a' ) ;
13+ expect ( node . value ) . toBe ( 'a' ) ;
14+ expect ( graph . nodes . size ) . toBe ( 1 ) ;
15+ } ) ;
16+
17+ it ( 'should not add duplicated values' , ( ) => {
18+ const node1 = graph . addVertex ( 'a' ) ;
19+ const node2 = graph . addVertex ( 'a' ) ;
20+ expect ( graph . nodes . size ) . toBe ( 1 ) ;
21+ expect ( node1 ) . toBe ( node2 ) ;
22+ } ) ;
23+ } ) ;
24+
25+ describe ( '#removeVertex' , ( ) => {
26+ beforeEach ( ( ) => {
27+ graph . addVertex ( 'a' ) ;
28+ } ) ;
29+
30+ it ( 'should remove vertex' , ( ) => {
31+ expect ( graph . removeVertex ( 'a' ) ) . toBe ( true ) ;
32+ expect ( graph . nodes . size ) . toBe ( 0 ) ;
33+ expect ( graph . removeVertex ( 'a' ) ) . toBe ( false ) ;
1334 } ) ;
1435 } ) ;
1536} ) ;
You can’t perform that action at this time.
0 commit comments