Allow graph edges with custom keys

This commit is contained in:
Alex Rock Ancelet 2019-12-18 08:37:24 +01:00
parent ba2d8dc4a8
commit 37f3d54aff
No known key found for this signature in database
GPG Key ID: 4A7B1CB0178A73F5
2 changed files with 26 additions and 9 deletions

View File

@ -2,22 +2,27 @@ export default class GraphEdge {
/**
* @param {GraphVertex} startVertex
* @param {GraphVertex} endVertex
* @param {number} [weight=1]
* @param {number} [weight=0]
* @param key
*/
constructor(startVertex, endVertex, weight = 0) {
constructor(startVertex, endVertex, weight = 0, key = null) {
this.startVertex = startVertex;
this.endVertex = endVertex;
this.weight = weight;
this.key = key;
}
/**
* @return {string}
*/
getKey() {
if (this.key) {
return this.key;
}
const startVertexKey = this.startVertex.getKey();
const endVertexKey = this.endVertex.getKey();
return `${startVertexKey}_${endVertexKey}`;
this.key = `${startVertexKey}_${endVertexKey}`;
return this.key;
}
/**
@ -35,6 +40,6 @@ export default class GraphEdge {
* @return {string}
*/
toString() {
return this.getKey();
return this.getKey().toString();
}
}

View File

@ -7,8 +7,6 @@ describe('GraphEdge', () => {
const endVertex = new GraphVertex('B');
const edge = new GraphEdge(startVertex, endVertex);
expect(edge.getKey()).toBe('A_B');
expect(edge.toString()).toBe('A_B');
expect(edge.startVertex).toEqual(startVertex);
expect(edge.endVertex).toEqual(endVertex);
expect(edge.weight).toEqual(0);
@ -39,4 +37,18 @@ describe('GraphEdge', () => {
expect(edge.endVertex).toEqual(vertexA);
expect(edge.weight).toEqual(10);
});
it('should return edges names as key', () => {
const edge = new GraphEdge(new GraphVertex('A'), new GraphVertex('B'), 0);
expect(edge.getKey()).toBe('A_B');
expect(edge.toString()).toBe('A_B');
});
it('should return custom key if defined', () => {
const edge = new GraphEdge(new GraphVertex('A'), new GraphVertex('B'), 0, 'custom_key');
expect(edge.getKey()).toEqual('custom_key');
expect(edge.toString()).toEqual('custom_key');
});
});