How can I make my D3 code cleaner
<p>i've managed to hack together a d3 transition, check it out here.</p>

<p><a href="https://jsfiddle.net/guanzo/k1xw6ace/14/" rel="nofollow">https://jsfiddle.net/guanzo/k1xw6ace/14/</a></p>

<p>Here's the basic idea:</p>

<p>I need to handle the possibility of 2 columns in case the svg height is not enough.</p>

<p>All transitions are a fade in/out and a translate +/- 30px on the x-axis;</p>

<p>On <code>initialLoad</code>, all legends transition into view.</p>

<p>When you click the "Reposition" button and data exits, exiting legends will immediately transition out, after the last legend exits the remaining legends will transition to their new position.</p>

<p>When you click the button again and data enters, updated legends will immediately transition to their new positions (taking into account entering legends), after the last update transition, the entering legends will transition in.</p>

<p>My problem is that my code is relying on setTimeouts and a couple hacks to deal with clumsy selections and conflicting enter/update states. </p>

<p><strong>For example</strong> when data enters i need to <code>selectAll</code> <code>update</code> AND <code>enter</code> legends, in order to determine their new position. However i need to set different transitions to both groups. </p>

<p>The transition order depends on if data is entering or exiting. If data is entering, the <code>update</code> selection transitions first, then the <code>enter</code> selection. if data is exiting, the <code>exit</code> selection transitions first, then the <code>update</code> selection. How do i elegantly code this inverse relationship?</p>

<p>I'm just confused on the best way to do this.</p>