@graph-ts/graph-lib
v1.6.0
Published
A functional TypeScript graphing library
Downloads
14
Readme
graph-lib
An immutable TypeScript graphing library.
Installation
To add graph-lib
to your project using npm:
$ npm install @graph-ts/graph-lib
Getting Started
In graph-lib
, graphs and the nodes and edges that comprise graphs are immutable. Rather than
mutating the state to, for example, add nodes and edges to a graph, a new graph object is created
each time the graph is modified.
import { newGraph, addNodes, addEdge, getNodes, getEdges, Graph, Node, Edge } from '@graph-ts/graph-lib';
const a: Node = { id: 'a' };
const b: Node = { id: 'b' };
const ab: Edge = { id: 'ab', source: 'a', target: 'b' };
const g0: Graph = newGraph();
const g1: Graph = addNodes(g0, [a, b]);
const g2: Graph = addEdge(g1, ab);
g0 === g1; // false
g1 === g2; // false
g0 === g2; // false
getNodes(g0); // []
getEdges(g0); // []
getNodes(g1); // [a, b]
getEdges(g1); // []
getNodes(g2); // [a, b];
getEdges(g2); // [ab]
a.id = 'c'; // throws error, these objects are now immutable
ab.source = 'b'; // throws error, these objects are now immutable
Why immutability?
Predictability! Redux! Time-travel! So many good reasons! I'll get to this part later...
What about performance?
Under the hood, graph-ts
uses Immer to enforce
immutability. It uses structural sharing, meaning that a completely new graph is not
actually generated each time a graph is modified; rather, the parts that are unchanged
between the two are structurally shared (the introductory blog post for Immer, found
here
is an excellent resource if you're curious how this works in practice). The implication
here is that you're unlikely to run into performance issues due to immutability. Quoting
that Immer introduction:
The usual mantra holds here: It is always better to optimize for Developer Experience then for Runtime Performance, unless proven by measurements that you need to do otherwise.