UNPKG

@figliolia/data-structures

Version:

Efficient data structures for every day programming

88 lines (87 loc) 2.52 kB
/** * Graph * * A generic graph construct for string and number values * * ```typescript * import { Graph, NodeCache } from "@figliolia/data-structures"; * * const cache = new NodeCache() * const root = cache.create(1); * const node2 = cache.create(2); * root.addEdge(node2); * root.addEdge(cache.create(4)); * node2.addEdge(cache.create(3)); * root.DFS(node => console.log(node.value)); // 1, 2, 3, 4 * root.BFS(node => console.log(node.value)); // 1, 2, 4, 3 * ``` */ export declare class Graph<T extends string | number> { value: T; edges: Map<T, Graph<T>>; constructor(value: T); /** * Add Edge * * Adds a graph node to the current node's edges */ addEdge(edge: Graph<T>): void; /** * Connects To * * Returns true if the current node has an edge matching the input value. * This lookup occurs in O(1) */ connectsTo(edge: T): boolean; /** * BFS * * Performs a breadth first search beginning with the current node. * Invokes the specified callback for each node visited */ BFS(callback: (node: Graph<T>) => void): void; /** * DFS * * Performs a depth first search beginning with the current node. * Invokes the specified callback for each node visited */ DFS(callback: (node: Graph<T>) => void): void; [Symbol.iterator](): Generator<[value: T, node: Graph<T>]>; } /** * Node Cache * * A mechanism for storing all graph nodes in a flat structure. When using * the NodeCache along side Graph nodes, you can access nodes using their * value's in O(1) regardless of where in the graph a node is positioned * * ```typescript * import { NodeCache, Graph } from "@figliolia/data-structures"; * * const cache = new NodeCache(); * cache.create(1); * cache.reference(1)?.addEdge?.(cache.create(2)); * * // Cache = { 1 => Graph<1>, 2 => Graph<2> }; * // Graph<1> = { value: 1, edges: { 2 => Graph<2> } } * ``` */ export declare class NodeCache<T extends string | number> { storage: Map<T, Graph<T>>; /** * Create * * Creates a graph node with the given value if it does not exist * in the cache. If a node with the provided value exists in the * cache, it is returned instead. */ create(value: T): Graph<T>; /** * Reference * * Returns a cached reference to a node with the provided value or * undefined if it does not exist */ reference(value: T): Graph<T> | undefined; }