title: What's the best data structure for grouping and ungrouping shapes
body: <p>I need to implement group/ungroup functionality in a graphic application. The aim is to be similar to the group/ungroup functionality in Adobe Illustrator or Microsoft PowerPoint.</p>
  
  <p>Groups can be nested (i.e.: a group can contain both elements and other groups, which in turn contain elements or groups)</p>
  
  <p>I am wondering what is the best data structure for doing that.</p>
  
  <p>It should be possible to tell quickly:</p>
  
  <ul>
  <li>whether an element is in a group</li>
  <li>its siblings in the widest group that contains it</li>
  </ul>
  
  <p>I am thinking of something like this:</p>
  
  <pre><code>{
      groups: {
          g1: ['n1', 'n2', 'n3'],
          g2: ['n4', 'n5', 'g1'],
          g3: ['g2', 'n6', 'n7']
      },
      nodes {
          n1: 'g1',
          n2: 'g1',
          n3: 'g1',
          n4: 'g2',
          n5: 'g2',
          g1: 'n1',
          g2: 'g3',
          n6: 'g3',
          n7: 'g3'
      }
  }
  </code></pre>
  
  <p>With <code>group</code> containing the groups themselves, and <code>nodes</code>acting as a lookup table to tell if a node is in a group. I could tell nodes and groups apart from their ID's (nodes are always numbers). Recursing through groups would provide lists of siblings.</p>
  
  <p>This would be encapsulated in an object that would then handle group, ungroup and checking - in JavaScript.</p>
  
  <p>Is this sane? Is there a better way?</p>