nl_tokens: This is a custom tree sorting algorithm . It uses the index property on each node to determine how to sort siblings . It uses the depth property plus the index to create a weight for each node . This weight algorithm has the limitation of not being able to go more then 80 levels in depth or more then 10k nodes per parent . The end result is a flat collection being correctly sorted based on this one single sort function .
pl_tokens: function ( node1 , node2 ) { // A shortcut for siblings if ( node1 . parentNode === node2 . parentNode ) { return ( node1 . data . index < node2 . data . index ) ? - 1 : 1 ; } // @NOTE: with the following algorithm we can only go 80 levels deep in the tree // and each node can contain 10000 direct children max var weight1 = 0 , weight2 = 0 , parent1 = node1 , parent2 = node2 ; while ( parent1 ) { weight1 += ( Math . pow ( 10 , ( parent1 . <mask> . depth + 1 ) * - 4 ) * ( parent1 . data . index + 1 ) ) ; parent1 = parent1 . parentNode ; } while ( parent2 ) { weight2 += ( Math . pow ( 10 , ( parent2 . data . depth + 1 ) * - 4 ) * ( parent2 . data . index + 1 ) ) ; parent2 = parent2 . parentNode ; } if ( weight1 > weight2 ) { return 1 ; } else if ( weight1 < weight2 ) { return - 1 ; } return ( node1 . data . index > node2 . data . index ) ? 1 : - 1 ; }