I was asked to create a jQuery plugin that would sort homogeneous DOM elements in a given DOM container element.
I came up with the idea to attach data-priority attribute to the elements that are to be sorted, e.g.:
<div class="offer-item" data-priority="10">..</div>
, and later use that attribute in a jQuery plugin.
The algorithm that I came up with works like this:
- Iterate over all elements that are to be sorted to find the element with the highest data-priority;
- Append that element to the container;
- Iterate over the remaining elements of the collection and find the element with the highest data-priority;
- Append the element to the container;
- ...continue like this recursively until the collection of elements is empty.
My plugin is initiated like this: $('.col-sm-6').sortItemsInContainer('.offer-item'); (it essentially says "sort all .offer-item items in .col-sm-6 container").
This is the code:
(function($) {
    $.fn.sortItemsInContainer = function(itemsSelector) {
        // Recursively sort DOM elements - highest priority on top
        var positionElements = function($items, $container) {
            if (0 === $items.length) {
                return;
            }
            var $highestEle = findHighestElement($items);
            $container.append($highestEle);
            $items = $items.not($highestEle);
            return positionElements($items, $container); // Recursive call
        };
        // Find DOM element with highest priority
        var findHighestElement = function($items) {
            var firstItem = $items.get(0);
            var $highest = $(firstItem);
            $.each($items, function() {
                var $current = $(this);
                if ($current.data('priority') > $highest.data('priority')) {
                    $highest = $current;
                }
            });
            return $highest;
        };
        return this.each(function() {
            var $container = $(this);
            var $itemsToSort = $container.children(itemsSelector);
            positionElements($itemsToSort, $container);
        });
    };
})(jQuery);
Now my questions are:
- Is my algorithm is optimal in terms of performance, or is it just terrible?
- Is there any other obvious and substantially more efficient way to accomplish this?
and lastly,
- I'd like to create some automated tests for this feature. Is this code testable? What would be the best way/technology to use in order to test it?


