« How GoogleNotebook Can Improve | Main

Chained Comparators in JavaScript

Currently on the Ladders search jobs results page, the sort options are chained together. For example, if you do a sort on company and then do a sort on location, the jobs will be sorted by location. But the jobs with the same location also are sorted by company. This is done by keeping track of the comparators executed. Each time a sort is executed, the comparator function is added to an array.

var allJobs = new Array(); //array containing all the job objects
var comparatorChain = new Array(); //array containing all the executed comparators

function sortByCompany()
{
    comparatorChain.push(companyNameSort);
    allJobs.sort(sortJobsFunction)
}

function companyNameSort(a, b)
{
    // code to compare company name
}

function sortByLocation()
{
    comparatorChain.push(locationSort);
    allJobs.sort(sortJobsFunction);
}

function locationSort(a, b)
{
    // code to compare location
}

function sortJobsFunction(a, b)
{
    var results = 0;

    for (var i = comparatorChain.length – 1; i >= 0; i--)
    {
        result = comparatorChain[i](a, b);
        if (result != 0)
        {
            return result;
        }
    }
    return result;
}

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)