{"id":16535155,"url":"https://github.com/devinivy/gert","last_synced_at":"2025-10-28T11:32:17.118Z","repository":{"id":57250030,"uuid":"44020314","full_name":"devinivy/gert","owner":"devinivy","description":"A graph library intended to delight you, Gert, and Arthur.","archived":false,"fork":false,"pushed_at":"2015-11-12T03:58:31.000Z","size":292,"stargazers_count":20,"open_issues_count":1,"forks_count":3,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-02-01T15:04:28.461Z","etag":null,"topics":["graph-theory","graphs","javascript"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/devinivy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-10-10T17:21:12.000Z","updated_at":"2024-01-14T12:40:07.000Z","dependencies_parsed_at":"2022-09-16T17:00:56.410Z","dependency_job_id":null,"html_url":"https://github.com/devinivy/gert","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devinivy%2Fgert","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devinivy%2Fgert/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devinivy%2Fgert/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/devinivy%2Fgert/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/devinivy","download_url":"https://codeload.github.com/devinivy/gert/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":238646293,"owners_count":19506989,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graph-theory","graphs","javascript"],"created_at":"2024-10-11T18:26:34.186Z","updated_at":"2025-10-28T11:32:11.807Z","avatar_url":"https://github.com/devinivy.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# gert\n\nA graph library intended to delight you, Gert, and Arthur.\n\n[![Build Status](https://travis-ci.org/devinivy/gert.svg?branch=master)](https://travis-ci.org/devinivy/gert) [![Coverage Status](https://coveralls.io/repos/devinivy/gert/badge.svg?branch=master\u0026service=github)](https://coveralls.io/github/devinivy/gert?branch=master)\n\n## Usage\nGert is here to help you create and traverse graphs of all shapes and sizes: directed, undirected, simple, self-looping, weighted, negative-weighted, unweighted, labeled, null, large, small, and the like.  For now it just has to be finite, but we're working on that.\n\nGert's interface aims to be understandable, lean, readable, and useful.  And the terminology used in Gert is consistent with \"the literature\", so if you're not familiar with what something means, combing the web or a relevant book should be sufficient to elucidate.\n\nA key feature of the library is that edges and vertices may be arbitrarily tagged and retrieved with an efficient labeling system.  If you dig into the API we think you'll find Gert to be quite the flexible little graph maestro.\n\n```js\nvar Graph = require('gert').Graph;\n\n// [ a ]--1-\u003e[ b ]--8-\u003e[ c ]\nvar graph = new Graph({\n    directed: true,\n    vertices: {\n        a: { labels: ['black'] },\n        b: { labels: ['black'] }\n    },\n    edges: [\n        ['a', 'b'],\n        { pair: ['b', 'c'], weight: 8 }\n    ]\n});\n\n// [ a ]\u003c-1--[ b ]\u003c-8--[ c ]\nvar transposed = graph.transpose();\nvar traversal = transposed.traverse('a');\n\ntraversal.hop('c').walk('b').walk('a');\n\ntraversal.sequence; // ['a', 'c', 'b', 'a']\ntraversal.distance; // 9 or (8 + 1)\n\ntransposed.equals(traversal.subgraph());  // true\ntransposed.getVertices('black');        // { a: {...}, b: {...} }\n```\n\n## API\n\n### `Gert.Graph`\nThe `Gert.Graph` object is the container for a graph consisting of vertices and edges, both of which can be tagged using a labeling system.  The edges may be directed or undirected, weighted or unweighted.\n\n#### `new Graph(definition)`\nCreates a new `Graph` object. Creates a null, directed graph when `definition` is not specified.  The `definition` is an object used to initialize the graph and contains the following information,\n - `directed` - if `false` indicates that the graph's edges are undirected rather than directed.  Defaults to `true`.\n - `vertices` - specifies the graph's vertices in one of two formats,\n  - an array of vertex ids (string or numeric) or,\n  - an object whose keys are vertex ids and whose values are objects of the form,\n    - `labels` - a label (string or numeric) or array of labels to place on this vertex.\n    - `data` - free-form data associated with this vertex.\n    - `to` - a vertex id or array of vertex ids to which edges should be created from this vertex.\n    - `from` - a vertex id or array of vertex ids from which edges should be created to this vertex.\n    - `neighbors` - a vertex id or array of vertex ids that should neighbor this vertex (it cannot include the id of this vertex).  Edges will be created between this vertex and the vertices specified.  Only for use in undirected graphs (`definition.directed = false`).\n\n- `edges` - an array of edge definitions, each edge specified in one of two formats,\n  - an edge-pair formed as an array of two vertex ids or,\n  - an object of the form,\n    - `pair` - an edge-pair formed as an array of two vertex ids (required).\n    - `labels` - a label (string or numeric) or array of labels to place on the edge.\n    - `weight` - a numeric weight to place on the edge.  Can be positive, negative, or zero.  Defaults to `1`.\n\nAny vertex ids that are only specified only in `to`, `from`, `neighbors` fields, or an edge `pair` will cause those vertices to be created in the graph without any `labels` or `data`.  The same edge may not be specified in a graph definition twice.  For example, the following definition is invalid because the edge between `a` and `b` is specified twice,\n```js\n// Invalid\nvar graph = new Graph({\n  vertices: {\n    a: { to: ['b'] },\n    b: { from: ['a'] }\n  }\n});\n```\n\n#### `graph.directed`\nIndicates whether the graph's edges are directed.  Should be considered read-only.\n\n#### `graph.vertexExists(v)`\nReturns `true` if a vertex with id `v` exists in the graph, and `false` otherwise.\n\n#### `graph.getVertex(v)`\nReturns vertex `v` in an object of the following format,\n - `id` - the vertex's id.\n - `labels` - an array of labels associated with the vertex.\n - `data` - any free-form data associated with the vertex.\n - `to` - an array of vertex ids to which there are outgoing edges from the vertex.\n - `from` - an array of vertex ids from which there are incoming edges to the vertex.\n - `neighbors` - an array of vertex ids of neighboring vertices.  This vertex property only appears in undirected graphs.\n - `outdegree` - the number of outgoing edges from the vertex.  This vertex property only appears in directed graphs.\n - `indegree` - the number of incoming edges to the vertex.  This vertex property only appears in directed graphs.\n - `degree` - the number of edges incident to the vertex, with self-loops counted twice.  This vertex property only appears in undirected graphs.\n\nIf no such vertex is found, returns `null`.\n\n#### `graph.getVertices(vertexIdsOrLabel, [onlyIds])`\nReturns an object whose keys are vertex ids and whose values are vertices of the format specified in [`graph.getVertex()`](#graphgetvertexv).  If `onlyIds` is specified as `true`, an array of unique vertex ids is returned instead.  When `vertexIdsOrLabel` is an array of vertex ids, the returned object/array will contain entries for every such vertex that is found in the graph.  If `vertexIdsOrLabel` is a label, the returned object/array will contain entries for all vertices that have that label.\n\n#### `graph.addVertex(v, [info])`\nAdds a new vertex into the graph where,\n - `v` - the vertex's id.\n - `info` - an object containing vertex info of the format,\n   - `labels` - a label (string or numeric) or array of labels to place on the vertex.\n   - `data` - free-form data associated with the vertex.\n\n#### `graph.updateVertex(v, info)`\nUpdates a vertex's labels and/or data where,\n - `v` - the vertex's id.\n - `info` - an object containing vertex info to be updated of the format,\n   - `labels` - a label (string or numeric) or array of labels to set on the vertex, removing all existing labels, or an object of the format,\n     - `add` - a label or array of labels to add to the vertex.\n     - `remove` - a label or array of labels to remove from the vertex.\n   - `data` - free-form data associated with this vertex.\n\nNote that label removals happen before label additions.\n\n#### `graph.removeVertex(v)`\nRemoves vertex with id `v` from the graph, including any incident edges.\n\n#### `graph.removeVertices(vertexIdsOrLabel)`\nRemoves a collection of vertices and their incident edges from the graph.  If `vertexIdsOrLabel` is an array of vertex ids, those vertices will be removed.  If `vertexIdsOrLabel` is a label, all vertices with that label will be removed.\n\n#### `graph.edgeExists(u, v)`\nReturns `true` if an edge from `u` to `v` exists in the graph, and `false` otherwise.  This method also accepts a single array argument containing the edge-pair (e.g. `[u, v]`).\n\n#### `graph.getEdge(u, v)`\nReturns the edge from vertex `u` to vertex `v` in an object of the following format,\n - `pair` - an array of two vertex ids representing the edge-pair.\n - `labels` - an array of labels associated with the edge.\n - `weight` - the edge's weight.\n\nIf no such edge is found, returns `null`.  This method also accepts a single array argument containing the edge-pair (e.g. `[u, v]`).  Note that if the graph is undirected, this returns the edge between vertex `u` and vertex `v` irrespective of their order.\n\n#### `graph.getEdges(edgePairsOrLabel, [onlyPairs])`\nReturns an array of edges in the format specified in [`graph.getEdge()`](#graphgetedgeu-v).  If `onlyPairs` is specified as `true`, each entry is an edge-pair (an array of two vertex ids) rather than a complete edge object.  When `edgePairsOrLabel` is an array of edge-pairs, there will be an entry for each such edge-pair that exists in the graph.  If `edgePairsOrLabel` is a label, there will be an entry for each edge that has the specified label.  The result contains a unique entry per edges; e.g. `graph.getEdges([['a', 'b'], ['a', 'b']])` will contain just one entry for the edge between `a` and `b` if such an edge exists.\n\n#### `graph.addEdge(u, v, [info])`\nAdds an edge into the graph from vertex `u` to vertex `v` with `info` an optional object of the format,\n - `labels` - a label (string or numeric) or array of labels to place on the edge.\n - `weight` - a numeric weight to place on the edge.  Can be positive, negative, or zero.  Defaults to `1`.\n\nThis method also accepts a single array argument containing the edge-pair (e.g. `[u, v]`) in lieu of the first two vertex arguments.\n\n#### `graph.updateEdge(u, v, info)`\nUpdates labels and/or weight of the edge from vertex `u` to vertex `v` where `info` is an object of the format,\n   - `labels` - a label (string or numeric) or array of labels to set on the edge, removing all existing labels, or an object of the format,\n     - `add` - a label or array of labels to add to the edge.\n     - `remove` - a label or array of labels to remove from the edge.\n   - `weight` - a numeric weight to set on the edge.\n\nThis method also accepts a single array argument containing the edge-pair (e.g. `[u, v]`) in lieu of the first two vertex arguments.  Note that label removals happen before label additions.\n\n#### `graph.removeEdge(u, v)`\nRemoves the edge that runs from vertex `u` to vertex `v`.  If the graph is undirected, this simply removes the edge that runs between vertices `u` and `v`.  This method also accepts a single array argument containing the edge-pair (e.g. `[u, v]`).\n\n#### `graph.removeEdges(edgePairsOrLabel)`\nRemoves a collection of edges from the graph.  If `edgePairsOrLabel` is an array of edge-pairs (each edge-pair an array of two vertex ids), those edges will be removed.  If `edgePairsOrLabel` is a label, all edges with that label will be removed.\n\n#### `graph.size()`\nReturns the number of edges in the graph.\n\n#### `graph.order()`\nReturns the number of vertices in the graph.\n\n#### `graph.equals(anotherGraph, [matchWeights])`\nReturns `true` when `anotherGraph` has the same graph structure and vertex ids, and returns `false` otherwise.  This ignores all labels and vertex data, but takes into account if the graphs are directed or not.  When `matchWeights` is `true`, it will require that edge weights also correspond for the two graphs to be considered equal.\n\nNote that this does not detect graph _isomorphism_ in general– matching vertex ids are used to compare the two graphs (e.g. if the two graphs are equal, vertex `u` in `graph` will necessarily map to vertex `u` in `anotherGraph`).\n\n#### `graph.snapshot()`\nReturns a new `Graph` representing a perfect copy `graph`, maintaining labels, edge weights, and data associated with vertices.  Vertex data is copied directly rather than being cloned.\n\n#### `graph.subgraph(subset)`\nReturns a new `Graph` representing a subgraph of `graph`, where `subset` is an object of the format,\n - `vertices` - an array of vertex ids to be included in the returned subgraph.\n - `edges` - an array of edge-pairs (each edge-pair an array of two vertex ids) to be included in the returned subgraph.\n\nLabels, data, and edge weights are all preserved in the subgraph.  The subgraph is directed if and only if `graph` is directed.\n\n#### `graph.complement()`\nReturns a new `Graph` representing the graph complement of `graph`.  All edges are unlabeled with weight `1`, and all vertices maintain their original labels and data.  Self-loops are preserved.\n\n#### `graph.transpose()`\nReturns a new `Graph` representing the graph transpose of `graph`.  Only for use with directed graphs.  All vertices maintain their original labels and data, and each edge inherits the labels and weight of its respective transposed edge from `graph`.\n\n#### `graph.union(anotherGraph)`\nReturns a new `Graph` representing the graph union of `graph` and `anotherGraph`.  Vertices with the same id merge into a single vertex with combined labels and copied, deeply merged vertex data.  Similarly, common edges merge into a single edge with combined labels, but weight inherited from the edge in `graph`.  Otherwise, vertex and edge information is inherited from its origin graph.  Both graphs must mutually directed or undirected.\n\n#### `graph.intersection(anotherGraph)`\nReturns a new `Graph` representing the graph intersection of `graph` and `anotherGraph`.  Vertex data and edge weight are inherited from `graph`, while labels from the two graphs are intersected per vertex and per edge.  Both graphs must mutually directed or undirected.\n\n#### `graph.join(anotherGraph, [weight], [oneWay])`\nReturns a new `Graph` representing the graph join of `graph` and `anotherGraph`.  When `weight` is specified, the edges constructed between the two graphs will be given that weight; otherwise they are given the default weight of `1`.  When the graphs are directed and `oneWay` is `true`, the edges constructed between the two graphs will only go from vertices in `graph` to vertices in `anotherGraph` but not vice-versa; by default edges are constructed in both directions.  The two graphs must be mutually directed or undirected and not share any common vertex ids.\n\n#### `graph.traverse([startingVertex], [record])`\nReturns a new `Traversal` of `graph`.  Optionally `startingVertex` may specify a vertex id within `graph` from which to begin the traversal.  In that case, `startingVertex` specifies the first visited vertex.  If `record` is `true`, traversal recording will be active (see [`traversal.record()`](#traversalrecord)).\n\n#### `graph.adjacencyMatrix([weighted])`\nReturns the graph's adjacency matrix as object of the format,\n - `vertices` - an array (ordering) of the vertex ids in `graph`.\n - `matrix` - an array of arrays, each representing a row in the adjacency matrix.  The vertex-order of the rows and columns corresponds to the order of the returned `vertices` property.  When `weighted` is `true`, the non-zero entries in the adjacency matrix contain the corresponding edge weight rather than `1`.\n\n\n### `Gert.Traversal`\nThe `Gert.Traversal` object is the container for traversing the vertices and edges of a graph.  It optionally records the traversal so that it can be replayed over another graph, and additionally emits useful [events](#events).  It also keeps track of some information about the trip, such as the total distance traveled.\n\n#### `new Traversal(graph)`\nCreates a new `Traversal` object.  The `graph` specified is the `Graph` that will be traversed.\n\n#### `traversal.graph`\nA reference the the `Graph` object being traversed.  The reference should not be reassigned, though the graph may be altered.\n\n#### `traversal.sequence`\nAn array of visited vertex ids in the order that they were visited.  Should be considered read-only.\n\n#### `traversal.distance`\nThe sum of the edge weights of the edges traversed using [`traversal.walk()`](#traversalwalkv).  Should be considered read-only.\n\n#### `traversal.recording`\nA boolean indicating if recording is currently active, per [`traversal.record()`](#traversalrecord) and [`traversal.stop()`](#traversalstop).  Should be considered read-only.\n\n#### `traversal.hop(v)`\nVisits vertex with id `v` without traversing any edges.  A new traversal might begin by calling `traversal.hop()` to visit the first vertex.  Returns `traversal`.\n\n#### `traversal.walk(v)`\nTraverses the edge from the current vertex to vertex with id `v`, visiting `v`.  Returns `traversal`.\n\n#### `traversal.currentVertex()`\nReturns vertex info (see [`graph.getVertex()`](#graphgetvertexv) for the format) of the currently visited vertex, or `null` if no vertex has been visited.\n\n#### `traversal.visits(v)`\nReturns the number of times the traversal has visited the vertex with id `v`.\n\n#### `traversal.visitedVertices()`\nReturns an array containing all visited vertex ids.  Differs from [`traversal.sequence`](#traversalsequence) in that it does not indicate order or contain duplicates.\n\n#### `traversal.subgraph()`\nReturns a `Graph` representing the subgraph of visited nodes and traversed edges.\n\n#### `traversal.record()`\nStart recording traversal.  Returns `traversal`.\n\n#### `traversal.stop()`\nStop recording traversal.  Returns `traversal`.\n\n#### `traversal.play([graph])`\nReturns a new `Traversal` of the recorded traversal steps played over `graph`.  It calls [`traversal.hop()`](#traversalhopv) and [`traversal.walk()`](#traversalwalkv) in the order they were called on `traversal` while recording was active.  If `graph` isn't specified, the traversal steps will be replayed over [`traversal.graph`](#traversalgraph).\n\n#### Events\nThe traversal object inherits from `Events.EventEmitter` and emits the following events,\n - `hop` - occurs when [`traversal.hop()`](#traversalhopv) has completed.  The event handler is passed the new then the previous current vertex ids.\n - `walk` - occurs when [`traversal.walk()`](#traversalwalkv) has completed. The event handler is passed the new then the previous current vertex ids.\n - `visit` - occurs when a vertex is visited by hopping or walking to it.  It is emitted directly after `hop` and `walk` events.  The event handler is passed the new current vertex id.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinivy%2Fgert","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdevinivy%2Fgert","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdevinivy%2Fgert/lists"}