From 14c9a8e4cfe923c39dc43025ab26321be7d53c37 Mon Sep 17 00:00:00 2001 From: Henning Dieterichs Date: Thu, 13 Feb 2020 16:55:20 +0100 Subject: [PATCH] Refactors createGraph, adds maxSize option --- data-extraction/src/js/helpers/createGraph.ts | 24 ++++++++++++++----- .../src/js/helpers/createGraphFromPointers.ts | 6 ++--- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/data-extraction/src/js/helpers/createGraph.ts b/data-extraction/src/js/helpers/createGraph.ts index 9f248dd..b2d279b 100644 --- a/data-extraction/src/js/helpers/createGraph.ts +++ b/data-extraction/src/js/helpers/createGraph.ts @@ -4,6 +4,8 @@ import { NodeGraphData, } from "../../CommonDataTypes"; +export type CreateGraphEdge = { to: T } & Omit; + /** * Given a list of roots, it creates a graph by following their edges recursively. * Tracks cycles. @@ -14,8 +16,9 @@ export function createGraph( item: T ) => { id?: string | number; - edges: ({ to: T } & Omit)[]; - } & Omit + edges: CreateGraphEdge[]; + } & Omit, + options: { maxSize?: number } = {} ): CommonDataTypes.Graph { const r: CommonDataTypes.Graph = { kind: { @@ -40,11 +43,13 @@ export function createGraph( return id; } - const queue = new Array(...roots); + const queue = new Array<{ item: T; dist: number }>( + ...roots.map(r => ({ item: r, dist: 0 })) + ); const processed = new Set(); while (queue.length > 0) { - const item = queue.shift()!; + const { item, dist } = queue.shift()!; if (processed.has(item)) { continue; } @@ -59,8 +64,15 @@ export function createGraph( from: fromId, to: toId, }); - if (!processed.has(e.to)) { - queue.push(e.to); + let shouldPush = !processed.has(e.to); + if ( + options.maxSize && + processed.size + queue.length > options.maxSize + ) { + shouldPush = false; + } + if (shouldPush) { + queue.push({ item: e.to, dist: dist + 1 }); } } } diff --git a/data-extraction/src/js/helpers/createGraphFromPointers.ts b/data-extraction/src/js/helpers/createGraphFromPointers.ts index 0cb537c..09ede33 100644 --- a/data-extraction/src/js/helpers/createGraphFromPointers.ts +++ b/data-extraction/src/js/helpers/createGraphFromPointers.ts @@ -1,5 +1,5 @@ -import { EdgeGraphData, NodeGraphData, CommonDataTypes } from "../.."; -import { createGraph } from "."; +import { NodeGraphData, CommonDataTypes } from "../../CommonDataTypes"; +import { CreateGraphEdge, createGraph } from "./createGraph"; /** * Given a labeled list of roots, it creates a graph by following their edges recursively. @@ -11,7 +11,7 @@ export function createGraphFromPointers( item: T ) => { id?: string | number; - edges: ({ to: T } & Omit)[]; + edges: CreateGraphEdge[]; } & Omit ): CommonDataTypes.Graph { const marker = {};