Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement traversal API for Graph #426

Merged
merged 6 commits into from
Oct 6, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/alfa-graph/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"@siteimprove/alfa-iterable": "^0.5.0",
"@siteimprove/alfa-json": "^0.5.0",
"@siteimprove/alfa-map": "^0.5.0",
"@siteimprove/alfa-option": "^0.5.0",
"@siteimprove/alfa-sequence": "^0.5.0",
"@siteimprove/alfa-set": "^0.5.0"
},
"devDependencies": {
Expand Down
89 changes: 79 additions & 10 deletions packages/alfa-graph/src/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Equatable } from "@siteimprove/alfa-equatable";
import { Iterable } from "@siteimprove/alfa-iterable";
import { Serializable } from "@siteimprove/alfa-json";
import { Map } from "@siteimprove/alfa-map";
import { Option } from "@siteimprove/alfa-option";
import { Sequence } from "@siteimprove/alfa-sequence";
import { Set } from "@siteimprove/alfa-set";

import * as json from "@siteimprove/alfa-json";
Expand Down Expand Up @@ -33,22 +33,20 @@ export class Graph<T>
return this._nodes.keys();
}

public neighbors(node: T): Option<Set<T>> {
return this._nodes.get(node);
public neighbors(node: T): Iterable<T> {
return this._nodes.get(node).getOr([]);
}

public has(node: T): boolean {
return this._nodes.has(node);
}

public add(node: T): Graph<T> {
const nodes = this._nodes;

if (nodes.has(node)) {
if (this.has(node)) {
return this;
}

return new Graph(nodes.set(node, Set.empty()));
return new Graph(this._nodes.set(node, Set.empty()));
}

public delete(node: T): Graph<T> {
Expand Down Expand Up @@ -86,12 +84,12 @@ export class Graph<T>
}

public disconnect(from: T, to: T): Graph<T> {
const nodes = this._nodes;

if (!nodes.has(from) || !nodes.has(to)) {
if (!this.has(from) || !this.has(to)) {
return this;
}

const nodes = this._nodes;

return new Graph(
nodes.set(
from,
Expand All @@ -103,6 +101,21 @@ export class Graph<T>
);
}

public traverse(
root: T,
traversal: Graph.Traversal = Graph.DepthFirst
): Sequence<T> {
return Sequence.from(traversal(this, root));
}

public hasPath(from: T, to: T): boolean {
if (!this.has(from) || !this.has(to)) {
return false;
}

return this.traverse(from).includes(to);
}

public equals(value: unknown): value is this {
return value instanceof Graph && value._nodes.equals(this._nodes);
}
Expand Down Expand Up @@ -158,4 +171,60 @@ export namespace Graph {
)
);
}

export interface Traversal {
<T>(graph: Graph<T>, root: T): Iterable<T>;
}

/**
* @see https://en.wikipedia.org/wiki/Depth-first_search
*/
export const DepthFirst: Traversal = function* <T>(graph: Graph<T>, root: T) {
const stack = [root];

let seen = Set.empty<T>();

while (stack.length > 0) {
const next = stack.pop()!;

if (seen.has(next)) {
continue;
}

yield next;

seen = seen.add(next);

for (const neighbor of graph.neighbors(next)) {
stack.push(neighbor);
}
}
};

/**
* @see https://en.wikipedia.org/wiki/Breadth-first_search
*/
export const BreadthFirst: Traversal = function* <T>(
graph: Graph<T>,
root: T
) {
const queue = [root];

let seen = Set.of(root);

while (queue.length > 0) {
const next = queue.shift()!;

yield next;

for (const neighbor of graph.neighbors(next)) {
if (seen.has(neighbor)) {
continue;
}

seen = seen.add(neighbor);
kasperisager marked this conversation as resolved.
Show resolved Hide resolved
queue.push(neighbor);
}
}
};
}
97 changes: 97 additions & 0 deletions packages/alfa-graph/test/graph.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,25 @@ import { test } from "@siteimprove/alfa-test";

import { Graph } from "../src/graph";

// foo
// |- bar
// |- baz
// |- foo
// |- ...
const graph = Graph.from([
["foo", ["bar", "baz"]],
["bar", []],
["baz", ["foo"]],
]);

test("#connect() connects two nodes in a graph", (t) => {
// foo
// |- bar
// |- baz
// |- ...
// |- baz
// |- foo
// |- ...
t.deepEqual(graph.connect("bar", "baz").toArray(), [
["baz", ["foo"]],
["foo", ["baz", "bar"]],
Expand All @@ -17,6 +29,11 @@ test("#connect() connects two nodes in a graph", (t) => {
});

test("#disconnect() disconnects two nodes in a graph", (t) => {
// foo
// |- baz
// |- foo
// |- ...
// bar
t.deepEqual(graph.disconnect("foo", "bar").toArray(), [
["baz", ["foo"]],
["foo", ["baz"]],
Expand All @@ -25,8 +42,88 @@ test("#disconnect() disconnects two nodes in a graph", (t) => {
});

test("#delete() removes a node from a graph", (t) => {
// foo
// |- baz
// |- foo
// |- ...
t.deepEqual(graph.delete("bar").toArray(), [
["baz", ["foo"]],
["foo", ["baz"]],
]);
});

test("#traverse() traverses the subgraph rooted at a node", (t) => {
t.deepEqual([...graph.traverse("baz")].sort(), ["baz", "foo", "bar"].sort());
});

test("#traverse() traverses the subgraph rooted at a node depth-first", (t) => {
// 1
// |- 2
// |- 3
// |- 4
// |- 5
// |- 6
// |- 7
const graph = Graph.from([
[1, [2, 5]],
[2, [3, 4]],
[5, [6, 7]],
]);

t.deepEqual(
[...graph.traverse(1, Graph.DepthFirst)],
[
1, // 1
5, // |- 5
7, // |- 7
6, // |- 6
2, // |- 2
3, // |- 3
4, // |- 4
]
);
});

test("#traverse() traverses the subgraph rooted at a node breadth-first", (t) => {
// 1
// |- 2
// |- 3
// |- 4
// |- 5
// |- 6
// |- 7
const graph = Graph.from([
[1, [2, 5]],
[2, [3, 4]],
[5, [6, 7]],
]);

t.deepEqual(
[...graph.traverse(1, Graph.BreadthFirst)],
[
1, // 1
2, // |- 2
5, // |- 5
4, // |- 4
3, // |- 3
6, // |- 6
7, // |- 7
]
);
});

test("#hasPath() checks if there's a path from one node to another", (t) => {
// foo -> bar
t.equal(graph.hasPath("foo", "bar"), true);

// baz -> foo -> bar
t.equal(graph.hasPath("baz", "bar"), true);

// bar has no neighbors
t.equal(graph.hasPath("bar", "baz"), false);

// A node always has a path to itself
for (const node of ["foo", "bar", "baz"]) {
t.equal(graph.hasPath(node, node), true);
}
});
2 changes: 1 addition & 1 deletion packages/alfa-graph/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"path": "../alfa-map"
},
{
"path": "../alfa-option"
"path": "../alfa-sequence"
},
{
"path": "../alfa-set"
Expand Down