久しぶりにJavaScriptを

どこかにありそうですけど、勉強のためにtableの中身をソートするJavaScriptを書いてみました。所要時間5時間くらいかな?JavaScriptでDOMをいじるのは簡単でいいですね。
汎用的に使えるようにしようと思ったのですが、JavaScriptのArray#sort()メソッドで文字列のソートと数値のソートを区別する必要があるため実装依存になってしまってます。ここをうまく整理できたら良いんですけど・・・。
とりあえず、現状のものを公開してみます。
使い方は、

var table;
window.onload = function() {
  table = new sortTable('sortTable');
  table.initialize();
}

としておいて、ソートする場所で以下のメソッドを呼びます。同じ引数で複数回呼び出すと、降順・昇順が入れ替わります。

table.sort(2);    //数値のソート
table.strSort(0); //文字列のソート

ソースは以下の通りです。

function $(id) { return document.getElementById(id); }

function sortTable(table_id) {
  this.initialize = function() {
    this.lastSortIndex = -1;
    this.lastSortOrder = true;
    
    this.tobj = table_id? $(table_id): document.getElementsByTagName('tbody')[0];
    this.min_index = 0;
    this.array = [];
    
    if (this.tobj.getElementsByTagName("th").length > 0) this.min_index = 1;
    for (var index = 0; index < this.tobj.rows.length; index++) {
      this.array.push(this.getRowData(this.tobj.rows[index]));
    }
  }
  this.getRowData = function(row) {
    if (row == null) return [];
    var data = [];
    for (var index = 0; index < row.cells.length; index++) {
      if (index == 3 || index > 4) {
        data.push(parseInt(row.cells[index].innerHTML));
      } else {
        data.push(row.cells[index].innerHTML);
      }
    }
    data.push(row.cells[row.cells.length - 1].className);
    return data;
  }
  
  this.show = function() {
    for (var row_idx = 0; row_idx < this.tobj.rows.length; row_idx++) {
      var row = this.tobj.rows[row_idx];
      for (var col_idx = 0; col_idx < row.cells.length; col_idx++) {
        row.cells[col_idx].innerHTML = this.array[row_idx][col_idx];
      }
      row.cells[row.cells.length - 1].className = this.array[row_idx][row.cells.length];
    }
  }
  
  this.sort = function(col) {
    var sortOrder = true;
    if (col == this.lastSortIndex) sortOrder = !this.lastSortOrder;
    
    this._sort(col, sortOrder);
    
    this.lastSortOrder = sortOrder;
    this.lastSortIndex = col;
  }
  this._sort = function(col, desc) {
    this.array.sort(function(a,b) {
      return (desc)? b[col] - a[col]: a[col] - b[col];
    });
    this.show();
  }
  
  this.strSort = function(col) {
    var sortOrder = false;
    if (col == this.lastSortIndex) sortOrder = !this.lastSortOrder;
    
    this._strSort(col, sortOrder);
    
    this.lastSortOrder = sortOrder;
    this.lastSortIndex = col;
  }
  this._strSort = function(col, desc) {
    this.array.sort(function(a,b) {
      if (a[col] > b[col]) return (desc)? -1: 1;
      if (a[col] < b[col]) return (desc)? 1: -1;
      return 0;
    });
    this.show();
  }
};