Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 526355c

Browse files
committedSep 5, 2024
add graph creation conveniences
1 parent 9129c34 commit 526355c

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
 

‎src/graph.js

+6
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,13 @@ export class Graph {
1616
return this.nodes.length-1;
1717
}
1818

19+
addUniqNode(type, props={}) {
20+
const nid = this.nodes.findIndex(node => node.type == type && node.props?.name == props?.name)
21+
return nid >= 0 ? nid : this.addNode(type, props)
22+
}
23+
1924
addRel(type, from, to, props={}) {
25+
if (from == null || to == null) return null
2026
const obj = {type, from, to, props};
2127
this.rels.push(obj);
2228
const rid = this.rels.length-1;

‎test/create.test.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
'use strict';
2+
3+
// Graph tests for graph creation conveniences
4+
// usage: deno test // from parent project's root dir
5+
6+
import {assertEquals } from "https://deno.land/std@0.126.0/testing/asserts.ts";
7+
import {Graph} from '../src/graph.js';
8+
9+
Deno.test("Adding Unique Nodes Only Once", () => {
10+
const g = new Graph();
11+
g.addNode('God')
12+
g.addNode('Man',{name:'Adam'})
13+
g.addNode('Woman',{name:'Eve'})
14+
assertEquals(g.size(), 3);
15+
g.addUniqNode('Man',{name:'Adam'})
16+
g.addUniqNode('God')
17+
assertEquals(g.size(), 3);
18+
});
19+
20+
Deno.test("Ignore Rels for Nodes Null or Undefined", () => {
21+
const g = new Graph();
22+
let nid = g.addNode('Man',{name:'Adam'})
23+
let rid = g.addRel('',nid,nid)
24+
assertEquals(rid, 0)
25+
rid = g.addRel('',null,nid)
26+
assertEquals(rid, null)
27+
rid = g.addRel('',nid,undefined)
28+
assertEquals(rid, null)
29+
});

0 commit comments

Comments
 (0)
Please sign in to comment.