Skip to content

Commit

Permalink
feat: 支持获取到图中某个节点的所有的子元素
Browse files Browse the repository at this point in the history
  • Loading branch information
pearone committed Dec 8, 2023
1 parent f9c5368 commit 0a11159
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 2 deletions.
3 changes: 3 additions & 0 deletions packages/event/__tests__/dag.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,7 @@ test('dag', () => {

console.log(dag.hasCycle());
console.log(dag.findParents(5));
console.log(dag.findParents(5, { include_self: false }));
console.log(dag.findChildren(4));
console.log(dag.findChildren(4, { include_self: false }));
});
2 changes: 1 addition & 1 deletion packages/event/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dpdfe/event-utils",
"version": "0.0.26",
"version": "0.0.27",
"description": "通用方法",
"author": "pearone",
"homepage": "https://github.com/DPDFE/react-layout/tree/main/packages/event",
Expand Down
59 changes: 58 additions & 1 deletion packages/event/src/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,12 +195,69 @@ class DAG {
return false;
}

/** 找到所有的子节点 */
findChildren(
node: OriginGraphNodeType,
options: {
/** 包含自己 */
include_self: boolean;
} = { include_self: true }
) {
const children: Set<OriginGraphNodeType> = new Set();
const stack: Set<OriginGraphNodeType> = new Set();

this.detectChild(node, children, stack);
if (!options.include_self) {
children.delete(node);
}
return children;
}

/** 获取子元素 */
detectChild(
node: OriginGraphNodeType,
visited: Set<OriginGraphNodeType>,
stack: Set<OriginGraphNodeType>
) {
if (stack.has(node)) {
// 如果当前节点已经在递归栈中
return;
}
if (visited.has(node)) {
// 如果当前节点已经访问过,则不需要再继续探索
return;
}

visited.add(node);
stack.add(node);

const children = this.children.get(node)!;

for (const parent of children.values()) {
if (this.detectChild(parent, visited, stack)) {
return true;
}
}

stack.delete(node);
return;
}

/** 找到所有的父节点 */
findParents(node: OriginGraphNodeType) {
findParents(
node: OriginGraphNodeType,
options: {
/** 包含自己 */
include_self: boolean;
} = { include_self: true }
) {
const parents: Set<OriginGraphNodeType> = new Set();
const stack: Set<OriginGraphNodeType> = new Set();

this.detectParent(node, parents, stack);
if (!options.include_self) {
parents.delete(node);
}
return parents;
}

Expand Down

0 comments on commit 0a11159

Please sign in to comment.