Skip to content

Commit

Permalink
fix: getNodeIdsConnected should remove duplicate values (#8054)
Browse files Browse the repository at this point in the history
* fix: getNodeIdsConnectedTo and getNodeIdsConnectedFrom should remove duplicate values

* feat: use seen set

Co-authored-by: Eric Eldredge <lettertwo@gmail.com>
  • Loading branch information
ahaoboy and lettertwo committed May 6, 2022
1 parent a71a2ae commit 504e546
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
15 changes: 12 additions & 3 deletions packages/core/graph/src/AdjacencyList.js
Expand Up @@ -439,14 +439,18 @@ export default class AdjacencyList<TEdgeType: number = 1> {
(Array.isArray(type)
? type.includes(this.#nodes.typeOf(node))
: type === this.#nodes.typeOf(node));

let nodes = [];
let seen = new Set<NodeId>();
let node = this.#nodes.head(from);
while (node !== null) {
if (matches(node)) {
let edge = this.#nodes.firstOut(node);
while (edge !== null) {
nodes.push(this.#edges.to(edge));
let to = this.#edges.to(edge);
if (!seen.has(to)) {
nodes.push(to);
seen.add(to);
}
edge = this.#edges.nextOut(edge);
}
}
Expand All @@ -473,12 +477,17 @@ export default class AdjacencyList<TEdgeType: number = 1> {
: type === this.#nodes.typeOf(node));

let nodes = [];
let seen = new Set<NodeId>();
let node = this.#nodes.head(to);
while (node !== null) {
if (matches(node)) {
let edge = this.#nodes.firstIn(node);
while (edge !== null) {
nodes.push(this.#edges.from(edge));
let from = this.#edges.from(edge);
if (!seen.has(from)) {
nodes.push(from);
seen.add(from);
}
edge = this.#edges.nextIn(edge);
}
}
Expand Down
12 changes: 12 additions & 0 deletions packages/core/graph/test/AdjacencyList.test.js
Expand Up @@ -57,6 +57,18 @@ describe('AdjacencyList', () => {
assert.deepEqual(graph.getNodeIdsConnectedTo(node1), [0, 2, 4, 5, 6]);
});

it('getNodeIdsConnectedTo and getNodeIdsConnectedFrom should remove duplicate values', () => {
let graph = new AdjacencyList();
let a = graph.addNode();
let b = graph.addNode();
let c = graph.addNode();
graph.addEdge(a, b);
graph.addEdge(a, c);
graph.addEdge(a, b, 2);
assert.deepEqual(graph.getNodeIdsConnectedFrom(a, -1), [b, c]);
assert.deepEqual(graph.getNodeIdsConnectedTo(b, -1), [a]);
});

it('removeEdge should remove an edge of a specific type from the graph', () => {
let graph = new AdjacencyList();
let a = graph.addNode();
Expand Down

0 comments on commit 504e546

Please sign in to comment.