Stacking selections in D3 with coffeescript

This function lays out the elements of a D3 selection such that they are touching either bottom to top, right to left, or both. It extends the d3.selection object so that it may be used as a chained method of the selection.

Bitbucket snippet

d3.selection::layout = (direction) ->  
    dx = 0
    dy = 0
    this.each ->
        el = this
        x = el.attr("x") ? 0
        y = el.attr("y") ? 0
        if direction in ["vertical","both"]
            y = dy
            el_height =
            dy += el_height
        if direction in ["horizontal","both"]
            x = dx
            el_width =
            dx += el_width
        el.attr "transform", "translate(#{x} #{y})"

You can use it as follows:

svg = "body"  
        .append "svg"
svg.attr "width", 300  
   .attr "height", 300
bg = svg.append "rect"  
bg.attr "width", 300  
  .attr "height", 300
  .style "fill", "#eef"
g = svg.append "g"  
g.attr "id", "parent"  
 .attr "transform", "translate(30,30)"

t1 = g.append "text" "dominant-baseline", "text-before-edge"  
  .text "some text"

r1 = g.append "rect"  
r1.attr "height", 32  
  .attr "width", 200
  .style "fill", "red"
  .style "opacity", 0.75

t2 = g.append "text"  
t2.attr "x", 0  
  .attr "y", 0
  .style "dominant-baseline", "text-before-edge"
  .text "some other text"