Skip to content

Commit

Permalink
fix(TreeData): 优化类型
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jan 3, 2021
1 parent 91147d2 commit e454d61
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions src/utils/TreeData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ export type TreeDataStandardNode<TNode extends TreeDataNode> = Merge<
export type TreeDataData<TNode extends TreeDataNode> = TNode[]

export type TreeDataChildrenPropName<TNode extends TreeDataNode> = {
[K in keyof TNode]: TNode[K] extends TreeDataData<TNode> ? K : never
[K in keyof TNode]: Exclude<TNode[K], undefined> extends TreeDataData<TNode>
? K
: never
}[keyof TNode]

export type TreeDataSearchStrategy = 'DFS' | 'BFS'
Expand Down Expand Up @@ -93,11 +95,13 @@ export type TreeDataTraverseFn<TNode extends TreeDataNode> = (
export class TreeData<TNode extends TreeDataNode> {
private data: TreeDataData<TNode>

private childrenPropName: TreeDataChildrenPropName<TNode>
private childrenPropName: TreeDataChildrenPropName<TNode> = 'children' as any

private searchStrategy: TreeDataSearchStrategy
private searchStrategy: TreeDataSearchStrategy = 'DFS'

private cloneIgnore: ((value: unknown) => boolean | undefined) | undefined
private cloneIgnore:
| ((value: unknown) => boolean | undefined)
| undefined = undefined

/**
* 构造函数。
Expand All @@ -109,10 +113,8 @@ export class TreeData<TNode extends TreeDataNode> {
data: TreeDataSingleRootData<TNode> | TreeDataMultipleRootData<TNode>,
options: TreeDataOptions<TNode> = {},
) {
this.cloneIgnore = options?.cloneIgnore
this.setOptions(options)
this.data = this.cloneDeep(Array.isArray(data) ? data : [data])
this.childrenPropName = options?.childrenPropName || ('children' as any)
this.searchStrategy = options?.searchStrategy || 'DFS'
}

private cloneDeep<T>(value: T): T {
Expand Down Expand Up @@ -220,6 +222,18 @@ export class TreeData<TNode extends TreeDataNode> {
}
}

/**
* 设置选项。
*
* @param options 选项
*/
setOptions(options: TreeDataOptions<TNode>): this {
this.cloneIgnore = options.cloneIgnore || this.cloneIgnore
this.childrenPropName = options.childrenPropName || this.childrenPropName
this.searchStrategy = options.searchStrategy || this.searchStrategy
return this
}

/**
* 遍历节点。
*
Expand Down

0 comments on commit e454d61

Please sign in to comment.