Skip to content

Commit

Permalink
Merge pull request #1271 from SergioCrisostomo/HTMLTableSort-additions
Browse files Browse the repository at this point in the history
custom sort function
  • Loading branch information
arian committed Jun 23, 2014
2 parents 94bf5a9 + b0a2bda commit 743a34d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
3 changes: 2 additions & 1 deletion Docs/Interface/HtmlTable.Sort.md
Expand Up @@ -54,13 +54,14 @@ Sorts a column.

### Syntax

myHtmlTable.sort(index, reverse, prepare);
myHtmlTable.sort(index, reverse, prepare[, sort]);

### Arguments

1. index - (*number*) the index of the column to sort
2. reverse - (*boolean*) reverses the sort if *true*; defaults to *false*
3. prepare - (*boolean*) if the sort has a secondary sort, set this value to *true* on the first sort, and *false* on the second. For example, if you sorted a directory list of files first by type and then secondly by file size, you would sort on type and pass *true* and then sort on size and pass *false*.
4. sort - (*function*, optional) this custom function will be used to sort the column. The parameters passed to _sort_ are objects with *position* and *value*.

### Returns

Expand Down
4 changes: 2 additions & 2 deletions Source/Interface/HtmlTable.Sort.js
Expand Up @@ -207,7 +207,7 @@ HtmlTable = Class.refactor(HtmlTable, {
return typeOf(parser) == 'string' ? HtmlTable.Parsers[parser] : parser;
},

sort: function(index, reverse, pre){
sort: function(index, reverse, pre, sortFunction){
if (!this.head) return;

if (!pre){
Expand All @@ -225,7 +225,7 @@ HtmlTable = Class.refactor(HtmlTable, {
this.body.dispose();
}

var data = this.parseData(parser).sort(function(a, b){
var data = this.parseData(parser).sort(sortFunction ? sortFunction : function(a, b){
if (a.value === b.value) return 0;
return a.value > b.value ? 1 : -1;
});
Expand Down
22 changes: 22 additions & 0 deletions Specs/Interface/HtmlTable.Sort.js
Expand Up @@ -160,6 +160,28 @@ describe('HtmlTable.Sort', function(){
expect(table.serialize()).toEqual({sortIndex: 0, sortReverse: false});
});

it('should allow a custom sort function', function(){
var table = new HtmlTable({
sortable: true,
headers: ['col'],
rows: [
['cccc'],
['bb'],
['aaa']
]
});

function customSort(a, b) { // sort by length of string
return a.value.length > b.value.length ? 1: -1;
}

table.sort(0, false, false, customSort);
var values = Array.map(table.body.rows, function(item){
return item.cells[0].get('text');
});
expect(values).toEqual(["bb", "aaa", "cccc"]);
});

it('should restore the sorted state of a table', function(){
var table = new HtmlTable({
sortable: true,
Expand Down

0 comments on commit 743a34d

Please sign in to comment.