diff --git a/README.md b/README.md index ec2aab6..d418bad 100644 --- a/README.md +++ b/README.md @@ -214,6 +214,14 @@ declare const removeVertex: (graph: Graph, vertex: string) => Graph; Removes a vertex from a graph. +### size + +```ts +declare const size: (graph: Graph) => number; +``` + +Returns the number of edges in the graph. + ### toD3 ```ts diff --git a/index.ts b/index.ts index 1a8b5a7..eb032d2 100644 --- a/index.ts +++ b/index.ts @@ -180,6 +180,20 @@ const removeVertex = (graph: Graph, vertex: string): Graph => { return result; }; +const size = (graph: Graph): number => { + let result = 0; + + for (let u in graph) { + for (let v in graph[u]) { + if (graph[u][v] > 0) { + result += 1; + } + } + } + + return result; +}; + const toD3 = (graph: Graph): D3Graph => { const nodes = []; const links = []; @@ -258,6 +272,7 @@ export { outdegrees, removeEdge, removeVertex, + size, toD3, topologicalSort, transpose, diff --git a/test.ts b/test.ts index d5e14e2..3a81cde 100644 --- a/test.ts +++ b/test.ts @@ -11,6 +11,7 @@ import { outdegrees, removeEdge, removeVertex, + size, toD3, topologicalSort, transpose, @@ -301,6 +302,29 @@ test("removeVertex", (t) => { ); }); +test("size", (t) => { + t.plan(3); + + t.equal(size({}), 0); + + t.equal( + size({ + a: { a: 1, b: 0 }, + b: { a: 0, b: 0 }, + }), + 1, + ); + + t.equal( + size({ + a: { a: 3, b: 0, c: 0 }, + b: { a: 0, b: 0, c: 0 }, + c: { a: 1, b: 0, c: 0 }, + }), + 2, + ); +}); + test("toD3", (t) => { t.plan(1); t.deepEqual(