Skip to content

Commit 978d9e8

Browse files
committed
Implement getAdjacentIds method for directed-graph
1 parent 49b88c2 commit 978d9e8

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

source/directed-graph/graph.test.ts

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -691,3 +691,50 @@ test('reverse() copies all nodes with their data', (t) => {
691691
}
692692
]);
693693
});
694+
695+
test('getAdjacentIds() returns an empty Set if the requested node doesn’t have any connections', (t) => {
696+
const graph = createGraphWithNodes({
697+
nodes: [['a', '']],
698+
connections: []
699+
});
700+
701+
const adjacentIds = graph.getAdjacentIds('a');
702+
703+
t.deepEqual(adjacentIds.values(), []);
704+
});
705+
706+
test('getAdjacentIds() returns all connected ids for the requested node', (t) => {
707+
const graph = createGraphWithNodes({
708+
nodes: [
709+
['a', ''],
710+
['b', ''],
711+
['c', ''],
712+
['d', ''],
713+
['f', '']
714+
],
715+
connections: [
716+
{ from: 'a', to: 'b' },
717+
{ from: 'a', to: 'c' },
718+
{ from: 'a', to: 'd' },
719+
{ from: 'b', to: 'f' }
720+
]
721+
});
722+
723+
const adjacentIds = graph.getAdjacentIds('a');
724+
725+
t.deepEqual(adjacentIds.values(), ['b', 'c', 'd']);
726+
});
727+
728+
test('getAdjacentIds() throws when the requested node doesn’t exist', (t) => {
729+
const graph = createGraphWithNodes({
730+
nodes: [['a', '']],
731+
connections: []
732+
});
733+
734+
try {
735+
graph.getAdjacentIds('a');
736+
t.fail('Expected getAdjacentIds() to fail but it did not');
737+
} catch (error: unknown) {
738+
t.is((error as Error).message, 'Node with id "a" doesn’t exist');
739+
}
740+
});

source/directed-graph/graph.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export type DirectedGraph<TId extends GraphNodeId, TData> = {
2525
isCyclic(): boolean;
2626
getTopologicalGenerations(): readonly (readonly TId[])[];
2727
reverse(): DirectedGraph<TId, TData>;
28+
getAdjacentIds(id: TId): ReadonlySet<TId>;
2829
};
2930

3031
function addAdjacentNodeId<TId extends GraphNodeId, TData>(
@@ -205,6 +206,11 @@ export function createDirectedGraph<TId extends GraphNodeId, TData>(): DirectedG
205206
nodes.set(id, { id, data, adjacentNodeIds: new Set(), incomingEdges: 0 });
206207
},
207208

209+
getAdjacentIds(id) {
210+
const node = getNode(id);
211+
return node.adjacentNodeIds;
212+
},
213+
208214
hasNode(id) {
209215
return nodes.has(id);
210216
},

0 commit comments

Comments
 (0)