Liquid Layouts and Matrix Transposition

Liquid layouts: the practice (among other things) of rendering a single ul/li group (like this):


  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
    <li>8</li>
    <li>9</li>
    <li>10</li>
    <li>11</li>
  </ul>

into a multi-column layout like this:
  
  1   2   3
  4   5   6
  7   8   9
  10  11
using CSS like this:

  <style type="text/css">
    ul {width: 30%}
    li {width: 33%; text-align: left; float: left}
  </style>
But what if you wanted the data sorted by column, not by row? For this, CSS is inadequate: it’s capable of flowing from left to right, top to bottom. So in order to acheive a column sorting, we need to re-sort the data, like this:

  <ul>
    <li>1</li>
    <li>5</li>
    <li>9</li>
    <li>2</li>
    <li>6</li>
    <li>10</li>
    <li>3</li>
    <li>7</li>
    <li>11</li>
    <li>4</li>
    <li>8</li>
    <li></li>
  </ul>
Using the same CSS, this would render:
  1   5   9
  2   6   10
  3   7   11 
  4   8
My new liquidity gem adds a “column_sort” method to the Array class, making it simple to re-sort your collection for a column-sorted liquid layout.

It achieves this by first copying then converting the array it’s called on into a list of n-rows, then performing a simple matrix transposition on it, then flattening the array again before returning.

For example, calling (1..11).to_a.column_sort(3) would perform the following transformations:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, nil]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, nil]]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, nil]]
[1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, nil]

Sunday, April 4, 2010 — 12 notes   ()
  1. so-arendt reblogged this from moonmaster9000
  2. moonmaster9000 posted this