Skip to content

Commit d2c87c0

Browse files
authored
Merge pull request #3 from things-dev/bugfix/getParentNodes
[Bugfix] getParentNode is acquiring another ancestral parent
2 parents c440e1b + 4181646 commit d2c87c0

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/node.ts

+8-1
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,13 @@ export class Node<T extends Data> {
1313
hasChildren: boolean;
1414

1515
#treeId: string;
16+
#ancestorPath: string;
1617
#key: string;
1718
#childKey: string;
1819

1920
constructor({
2021
treeId,
22+
ancestorPath,
2123
key,
2224
childKey,
2325
level,
@@ -26,6 +28,7 @@ export class Node<T extends Data> {
2628
data,
2729
}: {
2830
treeId: string;
31+
ancestorPath: string;
2932
key: string;
3033
childKey: string;
3134
level: number;
@@ -43,6 +46,7 @@ export class Node<T extends Data> {
4346
this.hasChildren = !this.isLeaf;
4447

4548
this.#treeId = treeId;
49+
this.#ancestorPath = ancestorPath;
4650
this.#key = key;
4751
this.#childKey = childKey;
4852
}
@@ -91,6 +95,7 @@ export class Node<T extends Data> {
9195
addChild({ data }: { data: T }): Node<T> {
9296
const newChildNode = new Node<T>({
9397
treeId: this.#treeId,
98+
ancestorPath: this.#ancestorPath,
9499
key: this.#key,
95100
childKey: this.#childKey,
96101
level: this.level + 1,
@@ -113,7 +118,9 @@ export class Node<T extends Data> {
113118
getParentNode(): Node<T> | undefined {
114119
const tree = this.getTree();
115120
const parentNode = tree.find(
116-
(node) => node.data[this.#key] === this.parentKey,
121+
(node) =>
122+
node.data[this.#key] === this.parentKey &&
123+
this.#ancestorPath.includes(node.#ancestorPath),
117124
);
118125
return parentNode;
119126
}

src/tree.ts

+9
Original file line numberDiff line numberDiff line change
@@ -140,13 +140,21 @@ export class Tree<T extends Data> {
140140
key,
141141
childKey,
142142
nodeParam,
143+
ancestorPath,
143144
}: {
144145
key: string;
145146
childKey: string;
146147
nodeParam: NodeParam<T>;
148+
ancestorPath?: string;
147149
}) {
150+
const path =
151+
ancestorPath === undefined
152+
? (nodeParam.data[key] as string)
153+
: ancestorPath;
154+
148155
const node = new Node<T>({
149156
treeId: this.treeId,
157+
ancestorPath: path,
150158
key,
151159
childKey,
152160
level: nodeParam.level,
@@ -156,6 +164,7 @@ export class Tree<T extends Data> {
156164
key,
157165
childKey,
158166
nodeParam: childNodeModel,
167+
ancestorPath: `${path}/${childNodeModel.data[key] as string}`,
159168
}),
160169
),
161170
data: nodeParam.data,

0 commit comments

Comments
 (0)