jQuery Generic Sorter

by amasad

HTML

<script src="https://github.com/mekwall/jquery-generic-sorter/raw/master/src/jquery.genericsorter.js"></script>
<script src="https://github.com/mekwall/jquery-generic-sorter/raw/master/src/comparators/alphanum.js"></script>
<script src="https://github.com/mekwall/jquery-generic-sorter/raw/master/src/comparators/natural.js"></script>

<strong>Numeric:</strong>
<ul>
    <li>5</li>
    <li>6</li>
    <li>10</li>
    <li>5</li>
</ul>

<br>

<strong>Basic:</strong>
<ul>
    <li>Beta</li>
    <li>Gamma</li>
    <li>Zeta</li>
    <li>Alpha</li>
</ul>

<br>

<strong>Natural:</strong>
<ul>
    <li>Beta</li>
    <li>Gamma</li>
    <li>Zeta</li>
    <li>Alpha</li>
</ul>

<br>

<strong>Alphanum:</strong>
<ul>
    <li>Beta</li>
    <li>Gamma</li>
    <li>Zeta</li>
    <li>Alpha</li>
</ul>

<br>

<strong>Weighted:</strong>
<ul>
    <li data-weight="1">Beta</li>
    <li data-weight="4">Gamma</li>
    <li data-weight="-1">Zeta</li>
    <li data-weight="3">Alpha</li>
</ul>
<br>
<div id="foo"></div>

<br>
<div id="bar"></div>

CSS

strong { font-weight: bold; }

JavaScript

(function($) {

    $.fn.sortElements = function( options ) {

        return $.genericSorter({
            comparator: options.comparator || "natural",
            source: this,
            extractor: options.extractor ||
                        function() {
                            return $(this).text();
                        },
            inverse: options.inverse || false
        }).sort().appendTo(this.parent().eq(0));
    };

})(jQuery);


$(function() {
    // lets try out the dom sorter
    $("ul:eq(0) li").sortElements({
        comparator: "numeric"
    });
    $("ul:eq(1) li").sortElements({
        comparator: "basic"
    });
    $("ul:eq(2) li").sortElements({
        comparator: "natural"
    });
    $("ul:eq(3) li").sortElements({
        comparator: "alphanum"
    });
    $("ul:eq(4) li").sortElements({
        comparator: "numeric",
        extractor: function(){return $(this).data('weight') || 0;}
    });
    // arrays of random data
    var testArr = [
        "Alpha",
        "Zeta",
        "Gamma",
        "Beta"
        ];
    var dates = [
        "2011-01-14",
        "2010-11-01",
        "1984-06-06",
        "2012-12-12"
        ];

    // lets instantiate the generic sorter
    var sorter = $.genericSorter();

    // load source and sort
    var sortedTestArr = sorter.source(testArr).sort();

    // change comparator and load another source
    sorter.comparator("natural").source(dates);
    var sortedDatesAsc = sorter.sort(false);
    var sortedDatesDesc = sorter.sort(true);

    $("#foo").text(sortedTestArr.toString());
    $("#bar").html("Ascending: " + sortedDatesAsc.toString() + "<br>Descending: " + sortedDatesDesc.toString());
});