@@ -16,15 +16,16 @@ function hasNextSibling(item, right) {
1616function fetchElement ( siblings , left , right , depth = 0 ) {
1717 dataArray . forEach ( ( item ) => {
1818 if ( item . left === left ) {
19- siblings . push ( item ) ;
20-
21- const currItem = siblings [ siblings . length - 1 ] ;
22- currItem . depth = depth ;
19+ const currItem = item ;
20+ let childs ;
2321
2422 if ( hasChild ( item ) ) {
25- currItem . childs = fetchElement ( [ ] , item . left + 1 , item . right - 1 , depth + 1 ) ;
23+ childs = fetchElement ( new Map ( ) , item . left + 1 , item . right - 1 , depth + 1 ) ;
2624 }
2725
26+ currItem . depth = depth ;
27+ siblings . set ( currItem , childs ) ;
28+
2829 if ( hasNextSibling ( item , right ) ) {
2930 siblings = fetchElement ( siblings , item . right + 1 , right , depth ) ;
3031 }
@@ -36,13 +37,13 @@ function fetchElement(siblings, left, right, depth = 0) {
3637function makeDocumentFragment ( nestedSetData ) {
3738 const fragment = document . createDocumentFragment ( ) ;
3839
39- function paste ( array ) {
40- array . forEach ( ( x ) => {
41- const op = new Option ( x . name , x . id ) ;
42- setLeftPadding . call ( op , x . depth * 2 ) ;
40+ function paste ( nestedSetMap ) {
41+ nestedSetMap . forEach ( ( value , key ) => {
42+ const op = new Option ( key . name , key . id ) ;
43+ setLeftPadding . call ( op , key . depth * 2 ) ;
4344 fragment . appendChild ( op ) ;
44- if ( x . childs ) {
45- paste ( x . childs ) ;
45+ if ( value ) {
46+ paste ( value ) ;
4647 }
4748 } ) ;
4849 }
@@ -56,7 +57,7 @@ fetch('https://sectors-enpoint.herokuapp.com/sectors')
5657 . then ( ( array ) => {
5758 dataArray = array . sort ( ( a , b ) => a . left - b . left ) ;
5859
59- const nestedSetData = fetchElement ( [ ] , 1 , dataArray . length * 2 ) ;
60- const fragment = makeDocumentFragment ( nestedSetData ) ;
60+ const nestedSetDataMap = fetchElement ( new Map ( ) , 1 , dataArray . length * 2 ) ;
61+ const fragment = makeDocumentFragment ( nestedSetDataMap ) ;
6162 select . appendChild ( fragment ) ;
6263 } ) ;
0 commit comments