graphs-for-js
Implementations of graph data structures for JavaScript and TypeScript
Features:
- Insert and remove nodes.
- Create edges by connecting and disconnecting nodes.
- Algorithms for graph data structures.
Table of contents generated with markdown-toc
Installation
$ npm install --save graphs-for-js
Graph Class Usage
Import the Graph
class to initialize a graph.
The library supports 4 types of graphs:
- Weighted, Directed graphs
- Edges go in one-direction and can be assigned a value.
- Unweighted, Directed graphs
- Edges go in one-direction and cannot be assigned a value.
- Weighted, Undirected graphs
- Edges are bidirectional and can be assigned value.
- Unweighted, Undirected graphs
- Edges are bidirectional and cannot be assigned a value.
For each of the above graph types, there are also readonly, immutable versions.
Import the GraphBuilder
// With require()const Graph = // With import syntax
Key Function
Because JavaScript does not natively hash/map objects and their contents to unique values as object keys, the GraphBuilder accepts a function for mapping a node value to a string key.
If a Key Function is not given, then the default behaviors on node values are the following:
- Primitive Types
- This includes number, string, boolean, symbol, null, and undefined.
- All primitives are converted to their string equivalents.
- Caution: Floats are subject to float-precision issues.
- Objects
- A string representation of the object is used as the key, for which the string contains properties including keys and values.
- For example, the object
{a: 32, b: 23}
is mapped as'{a:32,b:23}'
- If an object value is circular, then it is mapped as the value of
toString()
, normally'[object Object]'
JavaScript initialization
const weightedGraph = directed const unweightedGraph = directed
TypeScript initialization
Use the type parameters to specify the type of the nodes and of the edge values (if weighted).
.noKey.directed.weighted .noKey.directed.unweighted
You can also initiate a readonly graph which cannot be modified.
.noKey.readonly.directed .weighted // Specify edges and implicitly the nodes .noKey.readonly.directed .unweighted, // No edges, followed by an array of extra nodes.
Using the Graph
For the following examples, assume the nodes of graph
are numbers.
The examples show the differences among each type of graph when necessary.
Insert nodes
graph // Insert a single nodegraph // Insert multiple nodesconst result = graph // Use spread syntax for array inputs console // The number of nodes inserted
Removing nodes
graph // Remove a single nodegraph // Removes multiple nodesconst result = graph // Use spread syntax for array inputs console // The number of nodes removed
Number of nodes
graph
Forming edges
unweightedGraph // Creates an edge from node 1 to node 2 weightedGraph // Creates an edge from node 1 to node 2 with weight 0.5
Removing edges
unweightedGraph // Removes the edge from node 1 to node 2 weightedGraph // Removes the edge from node 1 to node 2weightedGraph // Removes the edge from node 1 to node 2 only if the weight of that edge is 0.5 undirectedGraphundirectedGraph // Will remove the edge from node 1 to node 2 in a unweighted graph.
Get all of the nodes and edges in the graph
graph.nodes // Returns an array of node valuesgraph.edges // Returns an array of edges /*type Edge<V, E> = { source: V, target: V, value: E, undirected: boolean}*/
Incoming and Outgoing edges
graph // Returns an array of edges whose source nodes are node 2graph // Returns an array of edges whose target nodes are node 2
Degree of Edge
graph // Degree of node 2graph // In-Degree of node 2graph // Out-Degree of node 2
Existence Methods
graph // Contains node 1graph // Contains all three nodes unweightedGraph // Has edge from node 1 to node 2 weightedGraph // Has edge from node 1 to node 2weightedGraph // Returns true if there is an edge from node 1 to node 2 AND edge value is 0.5 undirectedGraph === undirectedGraph // true
Edge Value
weightedGraph // Returns the value of the edge from nodes 1 to 4, if it exists.// If it does not exist, it returns undefined.
GraphUtil Usage
The GraphUtil
module contains some helper functions/algorithms that can be used on the graphs.
-
hasCycle(graph)
- Returns true if there is a cycle in the graph, false otherwise
-
findShortestPath(graph, start, end)
- Finds the shortest path from the node
start
to the nodeend
. Returns an object with the fieldspath
andpathLength
. If there exists a path, thenpath
is an array of nodes in that path in order fromstart
toend
, andpathLength
is the length of that path, i.e. the number of edges. If a path is not found, thenpath
is an empty array, andpathLength
is-1
.
- Finds the shortest path from the node
-
clone(graph)
- Creates a new instance of a graph that contains all nodes and edges in the given
graph
. The type of graph returned is the same type of graph given, e.g. if an undirected, unweighted graph is given, then the cloned graph will also be undirected and unweighted.
- Creates a new instance of a graph that contains all nodes and edges in the given
-
topologicalSort(graph)
- Topologically sorts the graph. Returns
undefined
if the given graph is not a DAG. Otherwise, it returns an array of nodes in topologically sorted order.
- Topologically sorts the graph. Returns
-
toAdjacencyMatrix(graph)
- Converts the given
graph
into an adjacency matrix. Returns an object with 5 values: -
- Converts the given
-
functional
utility functions:subset(graph, nodes)
- Returns a new subgraph instance that contains a subset of its original nodes, where each node in that subset is in
nodes
. - The return type of
subset
is the same as the return type forclone
.
- Returns a new subgraph instance that contains a subset of its original nodes, where each node in that subset is in
mapNodes(graph, callback, newKeyFn?)
- Creates a new graph instance whose nodes are the results of calling the given
callback
function on each node in the givengraph
. - The key function of the new graph is the given
newKeyFn
or the default key function if not given. - If 2 or more nodes result in the same key value (because of the callback function or the new key function), then those nodes are merged into one node, and each edge in those nodes are connected the newly merged node. If there was edge between two of those nodes, then the merged node will have a self loop.
- Creates a new graph instance whose nodes are the results of calling the given
mapEdges(graph, callback)
- Creates a new graph instance whose edge values are the results of calling the given
callback
function on each edge value in the givengraph
.
- Creates a new graph instance whose edge values are the results of calling the given
-
serialize
utility functions:stringify(graph)
- Creates a string using the nodes and edges of the graph.
parse(json)
- Creates a graph using a serialized representation of the graph.
Examples
const Graph GraphUtil = const graph = directed // Returns true if there exists a cycle in `graph`. Otherwise falseGraphUtil /* Finds the shortest path from the start node to the end node. Where V is the type of the node return type: { path: Array<V> // The nodes in the discovered path. If no path is found, then this array is empty. pathLength: number // The number of edges in the discovered path. If no path is found, then this is -1. }*/GraphUtil
Contributing
Feel free to contribute by adding changes to the graph implementation or by writing implementations for graph algorithms in GraphUtil
! You can also add suggestions or issues here
If you'd like to make changes to the graph implementation or for GraphUtil
:
-
Fork this repository
-
Create a feature branch
-
Make changes 🛠
-
Make a PR to merge into this repo
License
ISC © Anthony Yang