Skip to content

Commit

Permalink
feat: add tree for mock
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhouyangYe committed Mar 28, 2020
1 parent 84bbd9d commit 64909f6
Show file tree
Hide file tree
Showing 2 changed files with 117 additions and 0 deletions.
91 changes: 91 additions & 0 deletions packages/graphin/src/utils/Tree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
export interface Node {
id: string;
parent?: Node;
data?: any; // eslint-disable-line
children: Node[];
}

export default class Tree {
private root: Node | undefined;

private nodeIds: string[] = [];

constructor(root?: Node) {
// Pass in the root of an existing tree
if (root) this.root = root;
}

bfs = (cb: (node: Node) => boolean): Node | undefined => {
if (!this.root) {
return;
}

const queue: Node[] = [];

queue.push(this.root);
while (queue.length) {
const node = queue.shift() as Node;
if (cb(node)) {
return node;
}
if (node.children.length) {
queue.push(...node.children);
}
}
};

getRoot = (): Node | undefined => {
return this.root;
};

getNode = (id: string): Node | undefined => {
const result = this.bfs(node => {
return node.id === id;
});

return result;
};

// eslint-disable-next-line
private addRoot = (id: string, data?: any) => {
this.root = {
id,
data,
children: [],
};
this.root.parent = this.root;
this.nodeIds.push(id);
};

// eslint-disable-next-line
addNode = (conf: { parentId?: string; id: string; data?: any }) => {
const { parentId, id, data } = conf;
if (!this.root) {
this.addRoot(id, data);
return;
}

let parent;

if (!parentId) {
// If parentId was not given, pick a random node as parent
const index = Math.floor(Math.random() * this.nodeIds.length);
parent = this.getNode(this.nodeIds[index]);
} else {
parent = this.getNode(parentId);
}

if (!parent) {
console.error(`Parent node doesn't exist!`);
return;
}

this.nodeIds.push(id);
parent.children.push({
id,
data,
parent,
children: [],
});
};
}
26 changes: 26 additions & 0 deletions packages/graphin/src/utils/mock.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { NodeData, EdgeData, Data } from '../types';
import Tree from './Tree';

const defaultOptions = {
/** 鑺傜偣 */
Expand Down Expand Up @@ -116,6 +117,31 @@ export class Mock {
return this;
};

tree = () => {
this.edges = [];
const tree = new Tree();
const rootId = this.nodeIds[0];

this.nodeIds.forEach(id => {
tree.addNode({
id,
});
});

tree.bfs(node => {
if (node.id !== rootId) {
this.edges.push({
source: node.parent && node.parent.id,
target: node.id,
properties: [],
});
}
return false;
});

return this;
};

value = () => {
return {
nodes: this.nodes,
Expand Down

0 comments on commit 64909f6

Please sign in to comment.