HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptMinor

Too many JavaScript sort functions to accomplish the same type of sorting

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortingfunctionsthesamejavascripttootypemanysortaccomplish

Problem

You can see each list item has multiple attributes data-whatever. The user will choose from a dropdown box on how things should be sorted and the appropriate method is called. Is eval() the most appropriate choice for this or is there a better way?

$('#sort-options').change(function() {
    var sortType = $(this).val();
    var $selectedList = $($(".drop-zone.ui-tabs-selected a").attr('href')).find('.connectedSortable');
    var $listItems = $('li', $selectedList);

    //Sort
    var sortFunction = null;
    switch (sortType) {
    case 'custom': 
        $listItems.sort(sortCustom);
        break;
    case 'breed':
        $listItems.sort(sortBreed);
        break;
    case 'hatch':
        $listItems.sort(sortHatch);
        break;
    case 'laid':
        $listItems.sort(sortLaid);
        break;
    default:
        $listItems.sort(sortCustom);
    }

    //Empty UL
    $selectedList.empty();
    //Repopulate UL
    $.each($listItems, function(index, $listItem) {
        $selectedList.append($listItem);
    });
    });

    function sortCustom(a, b) {
    return $(a).attr('data-sort-order') - $(b).attr('data-sort-order');
    }

    function sortBreed(a, b) {
    return $(a).attr('data-breed') - $(b).attr('data-breed');
    }

    function sortHatch(a, b) {
    return $(a).attr('data-hatch') - $(b).attr('data-hatch');
    }

    function sortLaid(a, b) {
    return $(a).attr('data-laid') - $(b).attr('data-laid');
    }

    //Force initial sort
    $('#sort-options').trigger('change');
}

Solution

function makeSorter(sortType) {
    sortType = "data-"+sortType;
    return function (a, b) {
        return $(a).attr(sortType) - $(b).attr(sortType);
    };
}

$('#sort-options').change(function () {
    var sortType = $(this).val();
    var $selectedList = $($(".drop-zone.ui-tabs-selected a").attr('href')).find('.connectedSortable');
    var $listItems = $('li', $selectedList);

    $listItems.sort(makeSorter(sortType));


Note that if val is "custom" it won't work, so I recommend replacing "custom" with "sort-order".

Code Snippets

function makeSorter(sortType) {
    sortType = "data-"+sortType;
    return function (a, b) {
        return $(a).attr(sortType) - $(b).attr(sortType);
    };
}

$('#sort-options').change(function () {
    var sortType = $(this).val();
    var $selectedList = $($(".drop-zone.ui-tabs-selected a").attr('href')).find('.connectedSortable');
    var $listItems = $('li', $selectedList);

    $listItems.sort(makeSorter(sortType));

Context

StackExchange Code Review Q#10786, answer score: 2

Revisions (0)

No revisions yet.