filterTree 扩充深度优先

This commit is contained in:
rickcole 2020-04-20 17:19:26 +08:00
parent a1618cabde
commit 79b9e37539
2 changed files with 24 additions and 7 deletions

View File

@ -302,14 +302,18 @@ export default class NestedSelectControl extends React.Component<
const {options, labelField, valueField} = this.props;
const regexp = new RegExp(`${inputValue}`, 'i');
const iterator = (option: Option) =>
regexp.test(option[labelField || 'label']) ||
regexp.test(option[valueField || 'value']) ||
(!!option.children && option.children.some(iterator));
let filtedOptions =
inputValue && this.state.isOpened
? filterTree(options, iterator)
? filterTree(
options,
option =>
regexp.test(option[labelField || 'label']) ||
regexp.test(option[valueField || 'value']) ||
!!(option.children && option.children.length),
1,
true
)
: options.concat();
this.setState({

View File

@ -833,15 +833,28 @@ export function getTree<T extends TreeItem>(
export function filterTree<T extends TreeItem>(
tree: Array<T>,
iterator: (item: T, key: number, level: number) => boolean,
level: number = 1
level: number = 1,
depthFirst: boolean = false
) {
if (depthFirst) {
return tree
.map(item => {
let children: TreeArray | undefined = item.children
? filterTree(item.children, iterator, level + 1, depthFirst)
: undefined;
children && (item = {...item, children: children});
return item;
})
.filter((item, index) => iterator(item, index, level));
}
return tree
.filter((item, index) => iterator(item, index, level))
.map(item => {
if (item.children && item.children.splice) {
item = {
...item,
children: filterTree(item.children, iterator, level + 1)
children: filterTree(item.children, iterator, level + 1, depthFirst)
};
}
return item;