A graph is a collection of nodes and edges (circles and lines)

var graph = new Graph()

Graphs don't exist in 2D space (or any space), they are an abstract map showing connections between nodes.

§ Nodes and Edges

All of a graph's nodes and edges are stored in arrays called nodes and edges.
The types are Graph Node and Graph Edge.

graph.nodes = []  // array of GraphNode
graph.edges = [] // array of GraphEdge

This makes a new node. You can store a reference to it.

var node = graph.newNode()  // node is a GraphNode

A new edge needs to know the 2 nodes its connecting.

var edge = graph.newEdge(node1, node2)  // edge is a GraphEdge

§ Nodes

graph.nodes[0]  // the first node
graph.nodes.length // total number of nodes

This graph is interactive with the code below


Two nodes are adjacent if they are connected by an edge

§ Edges

An edge connects two nodes

graph.edges[0]  // the first edge
graph.edges.length // total number of edges

Ways that edges can be invalid:

  1. CIRCULAR an edge cannot connect a node to the same node
  2. DUPLICATE the same 2 nodes cannot have more than 1 edge between them

§ Remove


When removing a node, any edges which share the node will be removed also.


Removing an edge will do simply that and the nodes remain untouched.

§ Clean

graph.clean() // # of edges removed

Cleaning removes duplicate and circular edges. You can also target specific edges:

graph.removeEdge(edge)  // # of edges removed
graph.removeEdgeBetween(node1, node2) // # of edges removed

Removing Nodes:

graph.removeNode(node)  // # of nodes removed
graph.removeIsolatedNodes() // # of nodes removed

Isolated nodes are nodes that aren't connected to an edge.

var node = graph.mergeNodes(node1,node2) // node is a GraphNode