From 53f8c0dc24ada57274057a3dfb3958313c286173 Mon Sep 17 00:00:00 2001 From: Alex Rock Ancelet Date: Wed, 18 Dec 2019 08:37:24 +0100 Subject: [PATCH] Allow graph edges with custom keys --- src/data-structures/graph/GraphEdge.js | 19 ++++++++++++------- .../graph/__test__/GraphEdge.test.js | 16 ++++++++++++++-- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/src/data-structures/graph/GraphEdge.js b/src/data-structures/graph/GraphEdge.js index 9a5b5db4..c0002f0f 100644 --- a/src/data-structures/graph/GraphEdge.js +++ b/src/data-structures/graph/GraphEdge.js @@ -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(); } } diff --git a/src/data-structures/graph/__test__/GraphEdge.test.js b/src/data-structures/graph/__test__/GraphEdge.test.js index ceb84ab2..c2729845 100644 --- a/src/data-structures/graph/__test__/GraphEdge.test.js +++ b/src/data-structures/graph/__test__/GraphEdge.test.js @@ -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'); + }); });