Graphology: JavaScript Graph Library

0.26.0 · active · verified Tue Apr 21

Graphology is a comprehensive JavaScript library providing a robust and multipurpose Graph object. It implements a unified specification for various graph types, including directed, undirected, multi, and mixed graphs, making it a versatile tool for network analysis and graph theory applications. The library focuses on performance and memory efficiency, particularly when handling complex multigraph structures. The current stable version is 0.26.0, which introduced explicit ESM support and removed some internal dependencies. Releases are made periodically, incorporating performance enhancements, new features like additional degree methods, and refinements to its internal architecture. It distinguishes itself by offering a well-defined and consistent API for graph manipulation.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a directed graph, add nodes and edges with custom attributes, and perform basic operations like counting elements and iterating over nodes and edges.

import Graph from 'graphology';

interface NodeAttributes {
  label: string;
}

interface EdgeAttributes {
  weight: number;
}

// Create a new directed graph
const graph = new Graph<NodeAttributes, EdgeAttributes, any>({
  type: 'directed',
  multi: false
});

// Add nodes with attributes
graph.addNode('A', { label: 'Node A' });
graph.addNode('B', { label: 'Node B' });
graph.addNode('C', { label: 'Node C' });

// Add edges with attributes
graph.addEdge('A', 'B', { weight: 1 });
graph.addEdge('B', 'C', { weight: 2 });
graph.addEdge('C', 'A', { weight: 3 });

// Check graph properties
console.log(`Number of nodes: ${graph.order}`);
console.log(`Number of edges: ${graph.size}`);

// Iterate over nodes and their attributes
console.log('Nodes:');
graph.forEachNode((node, attributes) => {
  console.log(`- ${node} (Label: ${attributes.label})`);
});

// Iterate over edges and their attributes
console.log('Edges:');
graph.forEachEdge((edge, attributes, source, target) => {
  console.log(`- ${source} -> ${target} (Weight: ${attributes.weight})`);
});

// Get neighbors of a node
const neighborsOfB = graph.neighbors('B');
console.log(`Neighbors of B: ${neighborsOfB.join(', ')}`);

// Check if node exists
console.log(`Does node 'D' exist? ${graph.hasNode('D')}`);

view raw JSON →