* Remove lodash forEach usage

* Store built parents rather than deleting them
This commit is contained in:
Mike Jolley 2022-03-04 12:04:15 +00:00 committed by GitHub
parent 892d7c268d
commit c612b28e46
1 changed files with 8 additions and 6 deletions

View File

@ -1,7 +1,7 @@
/** /**
* External dependencies * External dependencies
*/ */
import { groupBy, keyBy, forEach } from 'lodash'; import { groupBy, keyBy } from 'lodash';
import { __, _n, sprintf } from '@wordpress/i18n'; import { __, _n, sprintf } from '@wordpress/i18n';
import { Fragment } from '@wordpress/element'; import { Fragment } from '@wordpress/element';
@ -44,6 +44,7 @@ export const buildTermsTree = (
): SearchListItemType[] | [ ] => { ): SearchListItemType[] | [ ] => {
const termsByParent = groupBy( filteredList, 'parent' ); const termsByParent = groupBy( filteredList, 'parent' );
const listById = keyBy( list, 'id' ); const listById = keyBy( list, 'id' );
const builtParents = [ '0' ];
const getParentsName = ( term = {} as SearchListItemType ): string[] => { const getParentsName = ( term = {} as SearchListItemType ): string[] => {
if ( ! term.parent ) { if ( ! term.parent ) {
@ -61,7 +62,7 @@ export const buildTermsTree = (
} )[] => { } )[] => {
return terms.map( ( term ) => { return terms.map( ( term ) => {
const children = termsByParent[ term.id ]; const children = termsByParent[ term.id ];
delete termsByParent[ term.id ]; builtParents.push( '' + term.id );
return { return {
...term, ...term,
breadcrumbs: getParentsName( listById[ term.parent ] ), breadcrumbs: getParentsName( listById[ term.parent ] ),
@ -74,11 +75,12 @@ export const buildTermsTree = (
}; };
const tree = fillWithChildren( termsByParent[ '0' ] || [] ); const tree = fillWithChildren( termsByParent[ '0' ] || [] );
delete termsByParent[ '0' ];
// anything left in termsByParent has no visible parent // Handle remaining items in termsByParent that have not been built (orphaned).
forEach( termsByParent, ( terms ) => { Object.entries( termsByParent ).forEach( ( [ termId, terms ] ) => {
tree.push( ...fillWithChildren( terms || [] ) ); if ( ! builtParents.includes( termId ) ) {
tree.push( ...fillWithChildren( terms || [] ) );
}
} ); } );
return tree; return tree;