util.ts
Overview
This utility file provides functionality centered around generating unique keys for grouping nodes, classifying nodes into combos based on relational edges, and verifying the existence of certain data structures. It primarily includes:
A KeyGenerator class to generate sequential alphabetical keys.
A Converter class that processes graph nodes and edges to assign nodes into "combo" groups.
Utility functions to check data validity and group nodes into combos based on community membership.
These utilities are useful in graph-related applications where nodes need to be categorized or grouped dynamically based on their connections or metadata.
Detailed Documentation
Class: KeyGenerator
Description
Generates sequential alphabetical keys starting from 'a' to 'z'. Designed to be used for assigning unique identifiers or labels in a simple incremental fashion.
Properties
idx: number — The current index used to track which character to generate next.
chars: string[]— Array of lowercase alphabets ['a', 'b', ..., 'z'].
Constructor
constructor()
Initializes the chars array with 26 lowercase English letters and sets idx to 0.
Methods
generateKey(): string
Generates and returns the next alphabetical key in sequence.
Returns:
string— A single lowercase letter representing the key.Usage Example:
const keyGen = new KeyGenerator(); console.log(keyGen.generateKey()); // Output: 'a' console.log(keyGen.generateKey()); // Output: 'b'Implementation Detail:
Usesthis.idxas an index to return the current character fromthis.charsand incrementsidxfor the next call.
Class: Converter
Description
Processes graph nodes and edges to classify nodes into groups ("combos") based on their edge relationships. It assigns a shared combo key to connected nodes.
Properties
keyGenerator: KeyGenerator— An instance ofKeyGeneratorfor generating combo keys.dict: Record<string, string>— A mapping from node ID to the combo key assigned.
Constructor
constructor()
Initializes a new KeyGenerator and creates an empty dictionary dict.
Methods
buildDict(edges: { source: string; target: string }[]): Record<string, string>
Assigns combo keys to nodes based on their edges.
Parameters:
edges— Array of edge objects, each withsourceandtargetnode IDs.Returns:
A dictionary mapping node IDs to their combo keys.Behavior:
For each edge, if one node already has a combo key and the other doesn't, assign the same key to the latter.
If neither node has a combo key, generate a new key and assign it to both.
If both have keys, no change is made.
Usage Example:
const converter = new Converter(); const dict = converter.buildDict([{source: '1', target: '2'}, {source: '2', target: '3'}]); console.log(dict); // Possible output: { '1': 'a', '2': 'a', '3': 'a' }
buildNodesAndCombos(nodes: any[], edges: any[]): { nodes: any[]; combos: any[] }
Generates updated nodes with combo assignments and a list of unique combo objects.
Parameters:
nodes: Array of node objects, each expected to have at least anidproperty.edges: Array of edge objects as perbuildDict.
Returns:
An object containing:nodes: Original nodes augmented with acomboproperty referencing assigned combo keys.combos: Array of combo objects with unique IDs and labels.
Behavior:
Calls
buildDictto assign combos.Maps nodes to include their combo key.
Extracts unique combos from the dictionary values and formats them as objects with an
idand label.
Usage Example:
const converter = new Converter(); const { nodes, combos } = converter.buildNodesAndCombos( [{id: '1'}, {id: '2'}, {id: '3'}], [{source: '1', target: '2'}, {source: '2', target: '3'}] ); console.log(nodes); // Nodes with combo 'a' attached console.log(combos); // [{ id: 'a', data: { label: 'Combo a' } }]
Function: isDataExist
Description
Checks if the given data object contains a non-boolean data property and a non-empty graph property inside data.
Signature
export const isDataExist = (data: any) => boolean;
Parameters
data: any— The data object to check.
Returns
boolean—trueifdata.dataexists, is not a boolean, anddata.data.graphis not empty; otherwise,false.
Usage Example
const data = { data: { graph: { nodes: [] } } };
console.log(isDataExist(data)); // true
Implementation Details
Uses Lodash's isEmpty to check if graph is empty.
Function: buildNodesAndCombos
Description
Creates combo groupings for nodes based on their communities property. Each unique community label results in a combo, and nodes are assigned the corresponding combo ID.
Signature
export const buildNodesAndCombos = (nodes: any[]) => { nodes: any[]; combos: any[] };
Parameters
nodes: any[]— Array of node objects, each potentially having acommunitiesarray.
Returns
Object containing:
nodes: Nodes augmented with acomboproperty (combo ID).combos: Array of combo objects with unique UUIDs and labels.
Behavior
Iterates over all nodes.
Extracts the first community from each node.
Creates a combo object for each unique community, generating a UUID for its ID.
Assigns combo IDs to nodes where applicable.
Usage Example
const nodes = [
{ id: '1', communities: ['group1'] },
{ id: '2', communities: ['group2'] },
{ id: '3', communities: ['group1'] },
];
const { nodes: updatedNodes, combos } = buildNodesAndCombos(nodes);
console.log(combos);
// [{ isCombo: true, id: 'uuid-1', data: { label: 'group1' } }, ...]
console.log(updatedNodes);
// Nodes with 'combo' property referencing combo IDs
Helper Function: findCombo
Extracts the first community string from a communities array.
Returns
undefinedif input is not an array.
Implementation Details & Algorithms
KeyGenerator uses a simple incremental index to generate keys from 'a' to 'z'. Note that after 26 calls,
idxwill exceed the alphabet range, which might be a limitation.Converter.buildDict uses a heuristic to assign the same combo key to connected nodes. It assumes edges define connected components and assigns combos accordingly.
Converter.buildNodesAndCombos constructs two outputs: nodes augmented with combo labels and unique combo objects for UI or downstream processing.
The standalone
buildNodesAndCombosfunction focuses on community-based grouping using UUIDs, which ensures unique combo IDs independent of alphabetical keys.isDataExistensures that graph data exists and is non-empty, preventing operations on invalid or incomplete data.
Interaction with Other System Parts
The file imports
lodashfor theisEmptyutility anduuidfor generating unique IDs.The classes and functions here are likely used as part of a graph or network visualization system where nodes must be grouped or combined based on relationships (
Converter) or metadata (buildNodesAndCombos).The generated combos (groups) can be used by UI components that render grouped nodes or combo boxes.
isDataExistis a guard function that likely helps other parts of the system decide whether to proceed with rendering or processing.
Visual Diagram: Function Flowchart
flowchart TD
A[Start] --> B[isDataExist(data)]
B -- true --> C[buildNodesAndCombos(nodes)]
C --> D[Return nodes with combo IDs and combos]
B -- false --> E[Return false or skip processing]
subgraph Converter
F[Converter Instance]
F --> G[buildDict(edges)]
G --> H[Assign combos to nodes]
H --> I[buildNodesAndCombos(nodes, edges)]
I --> J[Return nodes with combos and combo list]
end
style Converter fill:#f9f,stroke:#333,stroke-width:1px
Summary
util.ts provides utilities to generate keys, classify graph nodes into combos based on edges or community membership, and validate data structures. It supports graph processing workflows by grouping nodes for better visualization or analysis. The file is self-contained but relies on lodash and uuid libraries, and its output is designed to integrate with UI or graph modules that consume node and combo data.