Skip to content
Browse files

define comparator for sort() more correctly

  • Loading branch information...
1 parent 3967373 commit 1acb2147c283c5d0a0c7f1e0dd082acdae2f6152 @eldargab committed Mar 20, 2012
Showing with 24 additions and 13 deletions.
  1. +14 −7 lib/sort.js
  2. +10 −6 test/table.js
View
21 lib/sort.js
@@ -21,21 +21,28 @@ function KeysComparator (keys) {
sortFn = m[2];
}
- return function compare (a, b) {
- var va = a[key];
- var vb = b[key];
- var ret = 0;
- if (va > vb) ret = 1;
- if (va < vb) ret = -1;
+ return function (a, b) {
+ var ret = compare(a[key], b[key])
return sortFn == 'asc' ? ret : -1 * ret;
}
});
- return function compare (a, b) {
+ return function (a, b) {
for (var i = 0; i < comparators.length; i++) {
var res = comparators[i](a, b)
if (res != 0) return res;
}
return 0;
}
+}
+
+function compare (a, b) {
+ if (a === b) return 0;
+ if (a === undefined) return 1;
+ if (b === undefined) return -1;
+ if (a === null) return 1;
+ if (b === null) return -1;
+ if (a > b) return 1;
+ if (a < b) return -1;
+ return compare(String(a), String(b));
}
View
16 test/table.js
@@ -84,17 +84,21 @@ describe('Easy table', function () {
it('test .sort() function', function () {
t.cell('a', 1).newLine();
t.cell('a', 2).newLine();
+ t.cell('a', null).newLine();
+ t.cell('a', undefined).newLine();
t.sort(['a|des']);
- expectLine(3).be.equal('2');
- expectLine(4).be.equal('1');
+ expectLine(3).be.equal(' ');
+ expectLine(4).be.equal('null');
+ expectLine(5).be.equal('2 ');
+ expectLine(6).be.equal('1 ');
t.sort(['a']);
- expectLine(3).be.equal('1');
- expectLine(4).be.equal('2');
+ expectLine(3).be.equal('1 ');
+ expectLine(4).be.equal('2 ');
t.sort(['a|des']).sort(['a|asc']);
- expectLine(3).be.equal('1');
- expectLine(4).be.equal('2');
+ expectLine(3).be.equal('1 ');
+ expectLine(4).be.equal('2 ');
});
});

0 comments on commit 1acb214

Please sign in to comment.
Something went wrong with that request. Please try again.