{"id":18386456,"url":"https://github.com/stemmlerjs/unitgraphts","last_synced_at":"2025-04-07T00:33:08.153Z","repository":{"id":57385108,"uuid":"168410141","full_name":"stemmlerjs/UnitGraphTS","owner":"stemmlerjs","description":"Lightweight Typescript Graph Library","archived":false,"fork":false,"pushed_at":"2019-02-01T22:21:47.000Z","size":43,"stargazers_count":6,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-22T10:11:15.552Z","etag":null,"topics":["djikstra","graphs","recommendation-engine","typescript"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/stemmlerjs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-01-30T20:27:55.000Z","updated_at":"2022-03-27T22:53:51.000Z","dependencies_parsed_at":"2022-09-07T14:51:41.487Z","dependency_job_id":null,"html_url":"https://github.com/stemmlerjs/UnitGraphTS","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stemmlerjs%2FUnitGraphTS","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stemmlerjs%2FUnitGraphTS/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stemmlerjs%2FUnitGraphTS/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stemmlerjs%2FUnitGraphTS/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/stemmlerjs","download_url":"https://codeload.github.com/stemmlerjs/UnitGraphTS/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247574088,"owners_count":20960495,"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":["djikstra","graphs","recommendation-engine","typescript"],"created_at":"2024-11-06T01:22:06.419Z","updated_at":"2025-04-07T00:33:07.903Z","avatar_url":"https://github.com/stemmlerjs.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# UnitGraphTypeScript\n\n[![Build Status](https://travis-ci.org/keithwhor/UnitGraph.svg?branch=master)](https://travis-ci.org/keithwhor/UnitGraph)\n\nUnitGraph is a simple Graph traversal library for io.js. It is intended for\nquick, synchronous in-memory traversals including route tracing and finding\nclosest nodes to a target.\n\n## Installation\n\nUnitGraph is available via npm. Simply run `npm install ug-ts` and then:\n\n```javascript\nimport ug from 'ug-ts'\n```\n\nTo use the package. :)\n\n## Examples\n\n### Find all nodes of type 'person' with name matching 'ae'\n\n```javascript\nimport ug from 'ug-ts'\nlet graph = new ug.Graph();\n\ngraph.createNode('person', {name: 'Rachael'});\ngraph.createNode('person', {name: 'Stephanie'});\ngraph.createNode('person', {name: 'Michael'});\ngraph.createNode('person', {name: 'Donovan'});\n\ngraph.nodes('person').query().filter({name__ilike: 'ae'}).units();\n\n// [ Node (person {name: Rachael}), Node (person {name: Michael}) ]\n```\n\n### Find the shortest path between two nodes\n\n```javascript\nimport ug from 'ug-ts'\nlet graph = new ug.Graph();\n\nlet civilian = graph.createNode('person', {name: 'Clark Kent'});\nlet superman = graph.createNode('superhero', {name: 'Superman'});\ngraph.createEdge('wears_glasses').link(superman, civilian);\n\ngraph.trace(\n  graph.nodes('person').query().filter({name: 'Clark Kent'}).first(),\n  graph.nodes('superhero').query().filter({name: 'Superman'}).first()\n);\n// Path: Node (person {name: \"Clark Kent\"}) \u003c\u003c Edge (wears_glasses {}) \u003c\u003c Node (superhero {name: 'Superman'})\n```\n\n### Find all closest nodes, ordered by distance, of a certain type\n\n```javascript\nimport ug from 'ug-ts'\nlet graph = new ug.Graph();\n\nlet classification = graph.createNode('classification', {name: 'Sharing Economy'});\n\nlet corps = {\n  uber: graph.createNode('corporation', {name: 'Uber'}),\n  storefront: graph.createNode('corporation', {name: 'Storefront'}),\n  airbnb: graph.createNode('corporation', {name: 'AirBnB'})\n};\n\nlet industries = {\n  vc: graph.createNode('industry', {name: 'Venture Capital'}),\n  hospitality: graph.createNode('industry', {name: 'Hospitality'}),\n  taxi: graph.createNode('industry', {name: 'Taxi'})\n};\n\ngraph.createEdge('business_model').link(corps.uber, classification);\ngraph.createEdge('business_model').link(corps.airbnb, classification);\ngraph.createEdge('business_model').link(corps.storefront, classification);\ngraph.createEdge('emotion', {type: 'happy'}).link(industries.vc, classification);\ngraph.createEdge('emotion', {type: 'sad'}).link(industries.hospitality, classification);\ngraph.createEdge('emotion', {type: 'sad'}).link(industries.taxi, classification);\n\ngraph.closest(\n  graph.nodes('classification').query().first(), // grab Sharing Economy node\n  {\n    compare: function(node) {\n      // forget industries and uber!\n      return node.entity !== 'industry' \u0026\u0026 node.get('name') !== 'Uber';\n    },\n    direction: -1 // only track nodes that feed in to this one\n  }\n);\n\n// returns two paths, one from Sharing Economy \u003c\u003c (business_model) \u003c\u003c AirBnB\n//    and Sharing Economy \u003c\u003c business_model \u003c\u003c Storefront,\n//    ordered by their distance\n```\n\n## Documentation\n\n### Graph\n\n```javascript```\n\n```\nGraph()\n```\n\nConstructor. Part of the `ug` namespace. Use with `new` keyword, i.e.\n\n```javascript\nimport { Graph } from 'ug-ts'\nlet graph = new Graph();\n```\n\n#### Graph#unit\n\n```\nunit( [Number] uniqid )\n  returns [Unit] ([Node] or [Edge])\n```\n\nGrabs a unit (node or edge) by their unique id (automatically assigned by\n  their parent Graph object).\n\n#### Graph#nodeCount\n\n```\nnodeCount()\n  returns [Number]\n```\n\nReturns the total number of nodes that belong to the graph.\n\n#### Graph#edgeCount\n\n```\nedgeCount()\n  returns [Number]\n```\n\nReturns the total number of edges that belong to the graph.\n\n#### Graph#createNode\n\n```\ncreateNode( [String] entity, [Object] properties )\n  returns [Node]\n```\n\nCreates a node belonging to the parent graph, with entity type `entity` and\ncalls `Unit#load` to attach `properties` to the node.\n\nAutomatically creates a `NodeCollection` of type `entity` belonging to the\nparent graph if one does not yet exist.\n\n#### Graph#createEdge\n\n```\ncreateEdge( [String] entity, [Object] properties )\n  returns [Edge]\n```\n\nCreates an edge belonging to the parent graph, with entity type `entity` and\ncalls `Unit#load` to attach `properties` to the edge.\n\nAutomatically creates an `EdgeCollection` of type `entity` belonging to the\nparent graph if one does not yet exist.\n\n#### Graph#nodes\n\n```\nnodes( [String] entity )\n  returns [NodeCollection]\n```\n\nReturns the parent graph's `NodeCollection` object of the specified `entity`.\nInvoking this method will create a `NodeCollection` if one does not yet exist.\n\n#### Graph#edges\n\n```\nedges( [String] entity )\n  returns [EdgeCollection]\n```\n\nReturns the parent graph's `EdgeCollection` object of the specified `entity`.\nInvoking this method will create a `EdgeCollection` if one does not yet exist.\n\n#### Graph#trace\n\n```\ntrace( [Node] fromNode, [Node] toNode, [Number] direction )\n  returns [Path]\n```\n\nFinds the shortest distance `Path` from `fromNode` to `toNode`. If there are\nmultiple paths of the same distance, it will return the first one it finds.\n\n`direction` can be `-1` (incoming nodes only), `0` (doesn't matter) or `1`\n(outgoing nodes only).\n\nYou should not depend on this method to always return the same `Path`.\n\nFor finding all paths of a specific distance, use `Graph#closest`.\n\n#### Graph#closest\n\n```\nclosest( [Node] node, [Object] options )\n  returns [Array] of [Path]\n```\n\nFinds all closest nodes to `node` and returns their `Path`s in an array, ordered\nby total distance. Nodes are filtered based on the parameters passed in\n`options`.\n\nThese include:\n\n`options.compare`: A function containing a comparison constraint for the node.\n\nShould return `true` for an inclusion of the target node, and `false` to\nignore it.\n\nExample:\n\n```javascript\nlet options = {\n  compare: function(node) {\n    return node.entity === 'person';\n  }\n}\n```\n\nThis will make sure only nodes with the entity `'person'` are included in your\nresults.\n\n`options.count`: A number indicating the amount of results to return. 0 will\nreturn all results.\n\n`options.direction`: Which direction can we traverse the graph in?\nCan be `-1` (incoming nodes only), `0` (doesn't matter) or `1`\n(outgoing nodes only).\n\n`options.minDepth`: The minimum distance from our target at which to start\ncounting nodes in our result set.\n\n`options.maxDepth`: The maximum distance from our target at which we can finish\ncounting nodes in our result set.\n\n#### Graph#toJSON\n\n```\ntoJSON()\n  returns [String]\n```\n\nCreates a JSON string representation of our graph using the `toJSON` of graph\nconsituents.\n\n#### Graph#fromJSON\n\n```\nfromJSON( [String] json )\n  returns [self: Graph]\n```\n\nSynchronously prepares a graph from a `json` string representation.\n\n#### Graph#save\n\n```\nsave( [String] filename, [Function] callback )\n  returns [self: Graph]\n```\n\nSave the current graph to a file, asynchronously. Specify full path in `filename`.\n\n`callback` is of the form `function(err) {}`.\n\n#### Graph#load\n\n```\nload( [String] filename, [Function] callback )\n  returns [self: Graph]\n```\n\nLoad the current graph to a file, asynchronously, from `filename`.\n\n`callback` is of the form `function(err) {}`.\n\n---\n\n### Unit\n\n```\nUnit()\n```\n\n*Inaccessible* constructor. Base prototype for `Node` and `Edge`.\n\n#### Unit#load\n\n```\nload( [Object] properties )\n  returns [self: Unit]\n```\n\nLoad all properties for the `Unit` from `properties`. Creates a shallow copy\nof the object provided.\n\n#### Unit#set\n\n```\nset( [String] property, [Any] value )\n  returns [Any]\n```\n\nSet a specific property of the `Unit`. Returns the set property value.\n\n#### Unit#unset\n\n```\nunset( [String] property )\n  returns [Boolean]\n```\n\nUnsets `property` of the `Unit`. Returns `true` on success, `false` on failure.\n\n#### Unit#has\n\n```\nhas( [String] property )\n  returns [Boolean]\n```\n\nReturns `true` if `Unit` has property `property`, otherwise returns `false`.\n\n#### Unit#get\n\n```\nget( [String] property )\n  returns [Any]\n```\n\nReturns the associated property value of `Unit`.\n\n#### Unit#toString\n\n```\ntoString()\n  returns [String]\n```\n\nReturns a string representation of the `Unit`.\n\n#### Unit#valueOf\n\n```\nvalueOf()\n  returns [String]\n```\n\nSee: `Unit#toString`.\n\n---\n\n### Node\n\n```\nNode()\n  extends [Unit]\n```\n\n*Inaccessible* constructor. Inherits from `Unit`.\n\nUse `Graph#createNode` to invoke this constructor.\n\n#### Node#unlink\n\n```\nunlink()\n  returns true\n```\n\nDe-references all connected edges from itself, and itself from all connected\nedges.\n\n---\n\n### Edge\n\n```\nEdge()\n  extends [Unit]\n```\n\n*Inaccessible* constructor. Inherits from `Unit`.\n\nUse `Graph#createEdge` to invoke this constructor.\n\n#### Edge#link\n\n```\nlink( [Node] fromNode, [Node] toNode, [Boolean] duplex )\n  returns [self: Edge]\n```\n\nLinks two nodes directionally (`fromNode` to `toNode`) or bi-directionally\nif `duplex` is set to `true`.\n\n#### Edge#unlink\n\n```\nunlink()\n  returns true\n```\n\nDe-references both connected nodes from itself, and itself from both connected\nnodes.\n\n#### Edge#setDistance\n\n```\nsetDistance( [Number] distance )\n  returns [self: Edge]\n```\n\nSets the distance (length) of the edge.\n\n#### Edge#setWeight\n\n```\nsetWeight( [Number] weight )\n  returns [self: Edge]\n```\n\nSets the distance (length) of the edge to 1 / weight.\n\n#### Edge#oppositeNode\n\n```\noppositeNode( [Node] node )\n  returns [Node]\n```\n\nReturns the node opposite to the one provided (if provided node is connected to\n  the edge). Otherwise returns `undefined`.\n\n---\n\n### Collection\n\n```\nCollection()\n```\n\n*Inaccessible* constructor. Base prototype for `NodeCollection` and `EdgeCollection`.\n\n#### Collection#name\n\n```\nname()\n  returns [String]\n```\n\nReturns the entity name of the collection.\n\n#### Collection#indices\n\n```\nindices()\n  returns [Array] of [String]\n```\n\nProvides an array of all indexed fields in the collection\n\n#### Collection#createIndex\n\n```\ncreateIndex( [String] field )\n  returns [self: Collection]\n```\n\nAdds `field` as an index on the collection. Useful for `Collection#find` and\n`Collection#destroy`.\n\n#### Collection#createIndices\n\n```\ncreateIndex( [Array] fieldList )\n  returns [self: Collection]\n```\n\nAdds each `fieldList` entry as an index on the collection.\nUseful for `Collection#find` and `Collection#destroy`.\n\n#### Collection#find\n\n```\nfind( [String or Number] id )\nfind( [String] index, [String or Number] id )\n  returns [Unit] ([Node or Edge])\n```\n\nReturns the `Unit` (node or edge) associated with the supplied `index` and `id`.\n\nIf no `index` is provided, it will use the first index added to the Collection.\n\n#### Collection#destroy\n\n```\ndestroy( [String or Number] id )\ndestroy( [String] index, [String or Number] id )\n  returns [Unit] ([Node or Edge])\n```\n\nRemoves the `Unit` (node or edge) associated with the supplied `index` and `id`\nfrom the collection and returns it.\n\nIf no `index` is provided, it will use the first index added to the Collection.\n\n#### Collection#query\n\n```\nquery()\n  returns [Query]\n```\n\nCreates a new `Query` object with all units in the collection.\n\n---\n\n### NodeCollection\n\n```\nNodeCollection()\n  extends [Collection]\n```\n\n*Inaccessible* constructor. Inherits from `Collection`.\n\nUse `Graph#nodes(entity)` to invoke this constructor automatically.\n\n---\n\n### EdgeCollection\n\n```\nEdgeCollection()\n  extends [Collection]\n```\n\n*Inaccessible* constructor. Inherits from `Collection`.\n\nUse `Graph#edges(entity)` to invoke this constructor automatically.\n\n---\n\n### Query\n\n```\nQuery()\n  extends [Collection]\n```\n\n*Inaccessible* constructor. Inherits from `Collection`.\n\nUse `Collection#query` to instantiate this object.\n\n#### Query#filter\n\n```\nfilter( [Array] filtersObjects )\nfilter( [Object] filters_1, ..., [Object] filters_n )\n  returns [Query]\n```\n\nReturns a `Query` object containing a subset of `units` that has been filtered\nbased on supplied `filtersObjects`. Can be passed in as an array or separate\narguments.\n\nSee [DataCollection.js examples](https://github.com/thestorefront/DataCollection.js#more-examples)\nfor a better idea of how these filters work. Note: the implementations are not\ncompletely identical.\n\nSupported filters for UnitGraph's `Query` object are currently:\n\n```\nis\nnot\ngt\nlt\ngte\nlte\nilike\nlike\nin\nnot_in\n```\n\n#### Query#exclude\n\n```\nexclude( [Array] filtersObjects )\nexclude( [Object] filters_1, ..., [Object] filters_n )\n  returns [Query]\n```\n\nReturns the complementary set of units when compared to `Query#filter`.\n(Excludes instead of includes filter values).\n\n#### Query#first\n\n```\nfirst()\n  returns [Unit] ([Node or Edge])\n```\n\nReturns the first unit in the query set.\n\n#### Query#last\n\n```\nlast()\n  returns [Unit] ([Node or Edge])\n```\n\nReturns the last unit in the query set.\n\n#### Query#units\n\n```\nunits()\n  returns [Array] of [Unit] ([Node or Edge])\n```\n\nReturns all units in the query set.\n\n---\n\n### Path\n\n```\nPath()\n```\n\n*Inaccessible* constructor. Returned from `Graph#trace` and `Graph#closest`.\n\n#### Path#start\n\n```\nstart()\n  returns [Node]\n```\n\nReturns the first node in the path.\n\n#### Path#end\n\n```\nend()\n  returns [Node]\n```\n\nReturns the last node in the path.\n\n#### Path#length\n\n```\nlength()\n  returns [Number]\n```\n\nReturns an integer indicating the number of edges in the path.\n\n#### Path#distance\n\n```\ndistance()\n  returns [Number]\n```\n\nReturns a number indicating the total distance of the path.\n\n#### Path#prettify\n\n```\nprettify()\n  returns [String]\n```\n\nProvides a human-readable string representation of the path.\n\n#### Path#toString\n\n```\ntoString()\n  returns [String]\n```\n\nAlias for `Path#prettify`.\n\n## About\n\nThis project is maintained by myself, Khalil Stemmler, [@stemmlerjs](https://twitter.com/stemmlerjs).\n\nUnitGraphTypescript is MIT licenced, so have fun with it!\n\nThank you to the original author, Keith Horwood, [@keithwhor](https://twitter.com/keithwhor) for putting together the original version of this useful library.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstemmlerjs%2Funitgraphts","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstemmlerjs%2Funitgraphts","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstemmlerjs%2Funitgraphts/lists"}