Instantiation
Instantiating a graphology Graph object is merely an issue of requiring an implementation and calling it with some options.
Note that if you need to create a Graph using some serialized data or another Graph’s data, you should probably check the static #.from.
import Graph from 'graphology';
// Here you go:
const graph = new Graph();
// With options:
const graph = new Graph(options);
Options
- allowSelfLoops [boolean] true: should the graph allow self-loops?
- multi [boolean] false: Should the graph allow parallel edges?
- type [string] “mixed”: Type of the graph. One of
directed,undirectedormixed.
Examples
// Creating a multi-graph with no self-loops
const graph = new Graph({multi: true, allowSelfLoops: false});
Generics
The Graph class TypeScript declaration exposes three optional generics that you can use to restrict, in this order: node attributes, edge attributes and finally graph attributes.
The given types must extend Attributes, which is a shorthand for {[name: string]: any}.
type NodeAttributes = {
label: string;
color: string;
}
type EdgeAttributes = {
weight: number;
}
type GraphAttributes = {
name?: string;
}
const graph: Graph<NodeAttributes, EdgeAttributes, GraphAttributes> = new Graph();
Specialized constructors
Rather than providing tedious options to the constructor, one can use one of the many handy constructors provided by the implementation to create the desired graph:
import {MultiDirectedGraph} from 'graphology';
const myCustomGraph = new MultiDirectedGraph();
By default, the Graph object is a simple mixed graph, but here are the different naming “components” that you can use to instantiate a more complex graph:
- Graph with parallel edges?:
Multior none (simple graph). - Type of the graph?:
Directed,Undirectedor none (mixed graph).
Then to build the name, one must order the components likewise:
Multi? + Type? + Graph
List of all the specialized constructors
DirectedGraph
UndirectedGraph
MultiGraph
MultiDirectedGraph
MultiUndirectedGraph
Static #.from method
Alternatively, one can create a graph from a serialized graph or another Graph instance using the static #.from method:
Example
const graph = Graph.from(data);
// Need some options?
const graph = Graph.from(data, options);
// Also works with typed constructors
const graph = UndirectedGraph.from(data);
Arguments
- data Graph|SerializedGraph: pre-existing data to give to the constructor. This data can either be an existing
Graphinstance, and in this case both nodes & edges will be imported from the given graph, or a serialized graph whose format is described here. - options [object]: options passed to the created graph.
Note that graphology will throw an error if you try to instantiate a typed constructor using inconsistent options.