Skip to content

Commit 53f8c0d

Browse files
Pierstovaltrekhleb
authored andcommitted
Allow graph edges with custom keys
1 parent 4ba97b9 commit 53f8c0d

File tree

2 files changed

+26
-9
lines changed

2 files changed

+26
-9
lines changed

src/data-structures/graph/GraphEdge.js

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,27 @@ export default class GraphEdge {
22
/**
33
* @param {GraphVertex} startVertex
44
* @param {GraphVertex} endVertex
5-
* @param {number} [weight=1]
5+
* @param {number} [weight=0]
6+
* @param key
67
*/
7-
constructor(startVertex, endVertex, weight = 0) {
8+
constructor(startVertex, endVertex, weight = 0, key = null) {
89
this.startVertex = startVertex;
910
this.endVertex = endVertex;
1011
this.weight = weight;
12+
this.key = key;
1113
}
1214

13-
/**
14-
* @return {string}
15-
*/
1615
getKey() {
16+
if (this.key) {
17+
return this.key;
18+
}
19+
1720
const startVertexKey = this.startVertex.getKey();
1821
const endVertexKey = this.endVertex.getKey();
1922

20-
return `${startVertexKey}_${endVertexKey}`;
23+
this.key = `${startVertexKey}_${endVertexKey}`;
24+
25+
return this.key;
2126
}
2227

2328
/**
@@ -35,6 +40,6 @@ export default class GraphEdge {
3540
* @return {string}
3641
*/
3742
toString() {
38-
return this.getKey();
43+
return this.getKey().toString();
3944
}
4045
}

src/data-structures/graph/__test__/GraphEdge.test.js

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@ describe('GraphEdge', () => {
77
const endVertex = new GraphVertex('B');
88
const edge = new GraphEdge(startVertex, endVertex);
99

10-
expect(edge.getKey()).toBe('A_B');
11-
expect(edge.toString()).toBe('A_B');
1210
expect(edge.startVertex).toEqual(startVertex);
1311
expect(edge.endVertex).toEqual(endVertex);
1412
expect(edge.weight).toEqual(0);
@@ -39,4 +37,18 @@ describe('GraphEdge', () => {
3937
expect(edge.endVertex).toEqual(vertexA);
4038
expect(edge.weight).toEqual(10);
4139
});
40+
41+
it('should return edges names as key', () => {
42+
const edge = new GraphEdge(new GraphVertex('A'), new GraphVertex('B'), 0);
43+
44+
expect(edge.getKey()).toBe('A_B');
45+
expect(edge.toString()).toBe('A_B');
46+
});
47+
48+
it('should return custom key if defined', () => {
49+
const edge = new GraphEdge(new GraphVertex('A'), new GraphVertex('B'), 0, 'custom_key');
50+
51+
expect(edge.getKey()).toEqual('custom_key');
52+
expect(edge.toString()).toEqual('custom_key');
53+
});
4254
});

0 commit comments

Comments
 (0)