From ff8f9c49df70588f700789c8d47413d29b3ca45d Mon Sep 17 00:00:00 2001 From: Oleksii Trekhleb Date: Sat, 12 May 2018 10:35:54 +0300 Subject: [PATCH] Make it possible to delete all vertex edges at once. --- src/data-structures/graph/GraphVertex.js | 9 ++++++ .../graph/__test__/GraphVertex.test.js | 30 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/data-structures/graph/GraphVertex.js b/src/data-structures/graph/GraphVertex.js index 7389e6e6..b28ced32 100644 --- a/src/data-structures/graph/GraphVertex.js +++ b/src/data-structures/graph/GraphVertex.js @@ -119,6 +119,15 @@ export default class GraphVertex { return this.value; } + /** + * @return {GraphVertex} + */ + deleteAllEdges() { + this.getEdges().forEach(edge => this.deleteEdge(edge)); + + return this; + } + /** * @param {function} [callback] * @returns {string} diff --git a/src/data-structures/graph/__test__/GraphVertex.test.js b/src/data-structures/graph/__test__/GraphVertex.test.js index 1610e377..523d79ae 100644 --- a/src/data-structures/graph/__test__/GraphVertex.test.js +++ b/src/data-structures/graph/__test__/GraphVertex.test.js @@ -70,6 +70,36 @@ describe('GraphVertex', () => { expect(vertexA.getEdges().length).toBe(0); }); + it('should delete all edges from vertex', () => { + const vertexA = new GraphVertex('A'); + const vertexB = new GraphVertex('B'); + const vertexC = new GraphVertex('C'); + + const edgeAB = new GraphEdge(vertexA, vertexB); + const edgeAC = new GraphEdge(vertexA, vertexC); + vertexA + .addEdge(edgeAB) + .addEdge(edgeAC); + + expect(vertexA.hasEdge(edgeAB)).toBeTruthy(); + expect(vertexB.hasEdge(edgeAB)).toBeFalsy(); + + expect(vertexA.hasEdge(edgeAC)).toBeTruthy(); + expect(vertexC.hasEdge(edgeAC)).toBeFalsy(); + + expect(vertexA.getEdges().length).toBe(2); + + vertexA.deleteAllEdges(); + + expect(vertexA.hasEdge(edgeAB)).toBeFalsy(); + expect(vertexB.hasEdge(edgeAB)).toBeFalsy(); + + expect(vertexA.hasEdge(edgeAC)).toBeFalsy(); + expect(vertexC.hasEdge(edgeAC)).toBeFalsy(); + + expect(vertexA.getEdges().length).toBe(0); + }); + it('should return vertex neighbors in case if current node is start one', () => { const vertexA = new GraphVertex('A'); const vertexB = new GraphVertex('B');