Skip to content

Commit

Permalink
feat: add "subgraph" method (#70)
Browse files Browse the repository at this point in the history
  • Loading branch information
luckasnix authored Feb 16, 2025
1 parent a7abce8 commit 27bf4f4
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 3 deletions.
10 changes: 10 additions & 0 deletions docs/object-graph.doc.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ Returns a node of the object graph.

Returns a copy of the original object graph.

### subgraph()

Returns a subgraph of the original object graph.

#### Parameters

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| nodeKeys | `Array<string>` | - | __Required.__ The array of keys of the nodes to add to the object subgraph. |

### add()

Adds a node to the object graph.
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kasnix/structured-objects",
"version": "1.2.2",
"version": "1.3.0",
"repository": {
"type": "git",
"url": "git+https://github.com/luckasnix/structured-objects.git"
Expand Down
14 changes: 14 additions & 0 deletions src/object-graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,20 @@ export class ObjectGraph<NodeValue extends Record<string, unknown>> {
return new ObjectGraph(Array.from(this.nodes.values()), this.keyExtractor);
}

/**
* @description Returns a subgraph of the original object graph.
* @since 1.3.0
*/
public subgraph(nodeKeys: Array<string>): ObjectGraph<NodeValue> {
const subgraph = new ObjectGraph([], this.keyExtractor);
for (const [nodeKey, nodeValue] of this.nodes) {
if (nodeKeys.includes(nodeKey)) {
subgraph.add(nodeValue);
}
}
return subgraph;
}

/**
* @description Adds a node to the object graph.
* @since 1.0.0
Expand Down
10 changes: 10 additions & 0 deletions tests/object-graph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,16 @@ describe("copy()", () => {
});
});

describe("subgraph()", () => {
test("gets a subgraph of the original object graph", () => {
const shirtsObjectGraph = new ObjectGraph<Shirt>(shirtsMock, (shirt) => shirt.sku);
const shirtsObjectSubgraph = shirtsObjectGraph.subgraph(["1", "2", "3", "4"]);

expect(shirtsObjectGraph).toHaveLength(8);
expect(shirtsObjectSubgraph).toHaveLength(4);
});
});

describe("add()", () => {
test("logs an error when a node with the same key already exists in the object graph", () => {
const consoleErrorSpy = vi.spyOn(console, "error");
Expand Down

0 comments on commit 27bf4f4

Please sign in to comment.