diff --git a/README.md b/README.md index f171ed5..fd62b0f 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,14 @@ The `size` argument defines how many vertices with which to seed the graph. Addi The `id` function can be provided to specify how to generate ID's for each of the seed vertices. The `i` argument passed is the "index" of the vertex being created — a unique positive integer starting at 0, incrementing by 1 for each vertex. The default function will simply convert `i` to a string (`(i) => i.toString(10)`) resulting in ID's like: `"0"`, `"1"`, `"2"` etc. +### edges + +```ts +declare const edges: (graph: Graph) => Array<[string, string]>; +``` + +Returns an array of the edges in the graph. + ### fromD3 ```ts @@ -227,6 +235,14 @@ graph = transpose(graph); //=> [Graph] { A <- B <- C } ``` +### vertices + +```ts +declare const vertices: (graph: Graph) => Array; +``` + +Returns an array of the vertices in the graph. + ## Roadmap 1. Interactive demo. diff --git a/index.ts b/index.ts index 3172f65..c8fb467 100644 --- a/index.ts +++ b/index.ts @@ -73,6 +73,20 @@ const create = (size: number = 0, id: (i: number) => string = (i) => i.toString( }; }; +const edges = (graph: Graph): Array<[string, string]> => { + const result = []; + + for (let u in graph.adjacencyMatrix) { + for (let v in graph.adjacencyMatrix[u]) { + for (let i = 0; i < graph.adjacencyMatrix[u][v]; i++) { + result.push([u, v]); + } + } + } + + return result; +}; + const fromD3 = (d3Graph: D3Graph): Graph => { const size = d3Graph.nodes.length; const adjacencyMatrix: Graph["adjacencyMatrix"] = {}; @@ -256,12 +270,15 @@ const transpose = (graph: Graph): Graph => { }; }; +const vertices = (graph: Graph): Array => Object.keys(graph.adjacencyMatrix); + export { D3Graph, Graph, addEdge, addVertex, create, + edges, fromD3, indegrees, isCyclic, @@ -271,4 +288,5 @@ export { toD3, topologicalSort, transpose, + vertices, }; diff --git a/test.ts b/test.ts index 0f3cdcf..93303ac 100644 --- a/test.ts +++ b/test.ts @@ -2,6 +2,7 @@ import { addEdge, addVertex, create, + edges, fromD3, indegrees, isCyclic, @@ -11,6 +12,7 @@ import { toD3, topologicalSort, transpose, + vertices, } from "./index"; import test from "tape"; @@ -93,6 +95,25 @@ test("create", (t) => { ); }); +test("edges", (t) => { + t.plan(1); + + t.deepEqual( + edges({ + size: 3, + adjacencyMatrix: { + a: { a: 0, b: 1, c: 0 }, + b: { a: 0, b: 0, c: 1 }, + c: { a: 0, b: 0, c: 0 }, + }, + }), + [ + ["a", "b"], + ["b", "c"], + ], + ); +}); + test("fromD3", (t) => { t.plan(1); @@ -457,3 +478,19 @@ test("transpose", (t) => { }, ); }); + +test("vertices", (t) => { + t.plan(1); + + t.deepEqual( + vertices({ + size: 3, + adjacencyMatrix: { + a: { a: 0, b: 0, c: 0 }, + b: { a: 0, b: 0, c: 0 }, + c: { a: 0, b: 0, c: 0 }, + }, + }), + ["a", "b", "c"], + ); +});