2.3 KiB
2.3 KiB
Graph with Reflection and Rewrite Nodes
This library provides a simple directed graph implementation with two special node types:
- ReflectionNode – forwards all input values to its outputs unchanged.
- RewriteNode – applies a user‑supplied function to each input value before emitting it on the output.
Installation
npm install graph-reflection-rewrite
Usage
import { Graph, RewriteFunction } from 'graph-reflection-rewrite';
const graph = new Graph();
// Create a reflection node
const refNode = graph.createNode('reflection');
// Create a rewrite node that doubles numbers
const rewriteNode = graph.createNode('rewrite', {
func: (value: number) => value * 2
});
// Connect nodes
graph.addEdge(refNode.id, 'output', rewriteNode.id, 'input');
// Provide initial input to the reflection node
refNode.inputs.set('input', 5);
// Run the graph
graph.run();
// Inspect results
console.log(rewriteNode.outputs.get('input')); // 10
API
Graph
| Method | Description |
|---|---|
createNode(type, options?) |
Creates a node of the specified type. For rewrite nodes, options must contain a func property. |
addNode(node) |
Adds an existing node instance to the graph. |
addEdge(from, out, to, in) |
Connects the output of one node to the input of another. |
run() |
Executes all nodes in the graph, propagating data along edges. |
getNode(id) |
Retrieves a node by its ID. |
BaseNode
| Property | Type | Description |
|---|---|---|
id |
string |
Unique identifier. |
type |
string |
Node type (reflection or rewrite). |
inputs |
Map<string, any> |
Input values keyed by input names. |
outputs |
Map<string, any> |
Output values keyed by output names. |
process() |
void |
Override to implement node logic. |
ReflectionNode
- Inherits from
BaseNode. process()copies all inputs to outputs with the same keys.
RewriteNode
- Inherits from
BaseNode. - Constructor accepts a
func: (value: any) => any. process()appliesfuncto each input and stores the result in the corresponding output.
Testing
Run the test suite with:
npm test
The project uses Jest with TypeScript support (ts-jest).
License
MIT