Skip to content

Instantly share code, notes, and snippets.

@matheuslc
Created January 8, 2015 18:51
Show Gist options
  • Save matheuslc/ee3733f1202dcc80bba5 to your computer and use it in GitHub Desktop.
Save matheuslc/ee3733f1202dcc80bba5 to your computer and use it in GitHub Desktop.
Sort
;(function(window, document, jQuery) {
/** Table sort
* @description Sort items
*/
/** Insertion Sort Data Structure
* @description Sort numbers
* @param items {array} Array with integers
* @return items {array} Sorted array
*/
function insertionSort(items) {
var i = 0,
j = 0,
size = items.length,
sorted = [],
now = 0;
for(i = 0; i < size; i++) {
now = items[i];
for( j = i - 1; j > -1 && items[j] > now; j--) {
items[j+1] = items[j];
}
items[j+1] = now;
}
return items;
}
var clicked = false;
$('th').on('click', function() {
var items = [],
sorted = [],
suffix = $(this).attr('class')
.split(/\s+/)
.pop()
.split('-')
.pop();
$('.items-map-' + suffix).each(function(index) {
this.text = $(this).text();
((isNaN(+this.text)) ? items[index] = this.text : items[index] = +this.text);
});
// Check if it is an array with numbers or with strings
if(!isNaN(items[0])) {
sorted = insertionSort(items);
} else {
sorted = items.sort();
}
// Icons
$('th').find('.glyphicon').removeClass('glyphicon-chevron-up');
$('th').find('.glyphicon').addClass('glyphicon-chevron-down');
$(this).find('.glyphicon').removeClass('glyphicon-chevron-down');
$(this).find('.glyphicon').addClass('glyphicon-chevron-up');
// Reverse way
if(clicked) {
sorted = sorted.reverse();
$(this).find('.glyphicon').removeClass('glyphicon-chevron-up');
$(this).find('.glyphicon').addClass('glyphicon-chevron-down');
}
// Write sorted items
$('.items-map-' + suffix).each(function(index) {
$(this).text(sorted[index]);
});
((clicked) ? clicked = false : clicked = true);
});
})(window, document, $);
@matheuslc
Copy link
Author

Maybe a day have utility

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment