I'm completely stumped on the sort on page 298

I am deleting this entire original question because I accidentally hit the post instead of the save button that is so plain I missed it, and so all my edit was lost!

I figured out the one question but I am thinking the code below would get into an endless loop if two items to sort were equal because it never returns a 0 to alert the javascript sort function that the two items are equal… Is this correct?

The code …

$(document).ready(function() {
$(‘#ascending’).click(function() {
SORTER.sort(‘.sortable’);
});
$(‘#descending’).click(function() {
SORTER.sort(‘.sortable’, ‘desc’);
});
});

var SORTER = {};
SORTER.sort = function(which, dir) {
SORTER.dir = (dir == “desc”) ? -1 : 1;
$(which).each(function() {
// Find the list items and sort them
var sorted = $(this).find(“> li”).sort(function(a, b) {
return $(a).text().toLowerCase() > $(b).text().toLowerCase() ? SORTER.dir : -SORTER.dir;
});
$(this).append(sorted);
});
};

This line here is where the comparison occurs.


return $(a).text().toLowerCase() > $(b).text().toLowerCase() ? SORTER.dir : -SORTER.dir;

It returns one value when it’s greater, if it’s not (therefore being less than or equal to) returns the other value.

There doesn’t appear to be any conflict.

After fighting to correct all the errors in my post that hide till I hit submit, I forgot to mention that this code is from page 298 of the Novice To Ninja book from SitePoint.

There’s no conflict, its just that there are three possible values to return when sorting according to page 299, those are 1 to indicate that a is > b, -1 to indicate that a < b, and a third value = to indicate that a equals b. The third value of 0 is not needed here.

I just did testing of this to see if two items of equal value caused a problem. It did not, I guess sort is smarter than that. :smiley:

t.