Skip to content
Browse files

cache calculated sort values

  • Loading branch information...
1 parent b83d930 commit ad5ca040401e136866d41840c1430354894240a0 @kylefox committed
Showing with 44 additions and 15 deletions.
  1. +12 −3 index.html
  2. +32 −12 jquery.tablesort.js
View
15 index.html
@@ -19,7 +19,7 @@
</head>
<body>
-<table>
+<!-- <table>
<thead>
<tr>
<th>Name</th>
@@ -54,7 +54,7 @@
<td>37</td>
</tr>
</tbody>
-</table>
+</table> -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
@@ -64,10 +64,19 @@
var sort;
$(function() {
+
+ var table = $('<table></table>');
+ table.append('<thead><tr><th class="number">Number</th></tr></thead>');
+ var tbody = $('<tbody></tbody>');
+ for(var i = 0; i<500; i++) {
+ tbody.append('<tr><td>' + Math.floor(Math.random() * 100) + '</td></tr>');
+ }
+ table.append(tbody);
+ $('body').append(table);
+
sort = $('table').tablesort().data('tablesort');
$('thead th.number').data('sortBy', function(th, td, sorter) {
- console.log("sort by number!");
return parseInt(td.text(), 10);
});
View
44 jquery.tablesort.js
@@ -1,13 +1,5 @@
$(function() {
- function bm(f) {
- var s = new Date(),
- e;
- f();
- e = new Date();
- return e.getTime() - s.getTime();
- }
-
function debug(msg) {
if(console && console.log) {
console.log('[tablesort] ' + msg);
@@ -35,10 +27,16 @@ $(function() {
SortableTable.prototype = {
sort: function(th) {
- var self = this,
+ var start = new Date(),
+ self = this,
table = this.$el,
rows = table.find('tbody tr'),
- direction;
+ direction,
+ aRow,
+ bRow,
+ aIndex,
+ bIndex,
+ cache = [];
if(rows.length === 0)
return;
@@ -46,11 +44,31 @@ $(function() {
this.index = th.index();
this.direction = this.direction === 'asc' ? 'desc' : 'asc';
direction = this.direction == 'asc' ? 1 : -1;
+
debug("Sorting by " + this.index + ' ' + this.direction);
rows.sort(function(a, b) {
- a = sortValueForCell(th, self.cellToSort(a), self);
- b = sortValueForCell(th, self.cellToSort(b), self);
+ aRow = $(a);
+ bRow = $(b);
+ aIndex = aRow.index();
+ bIndex = bRow.index();
+
+ // Sort value A
+ if(cache[aIndex]) {
+ a = cache[aIndex];
+ } else {
+ a = sortValueForCell(th, self.cellToSort(a), self);
+ cache[aIndex] = a;
+ }
+
+ // Sort Value B
+ if(cache[bIndex]) {
+ b = cache[bIndex];
+ } else {
+ b = sortValueForCell(th, self.cellToSort(b), self);
+ cache[bIndex]= b;
+ }
+
if(a > b) {
return 1 * direction;
} else if(a < b) {
@@ -64,6 +82,8 @@ $(function() {
table.append(tr);
});
+ debug('Sort finished in ' + ((new Date()).getTime() - start.getTime()) + 'ms');
+
},
cellToSort: function(row) {

0 comments on commit ad5ca04

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