Skip to content

Instantly share code, notes, and snippets.

@andrewbranch
Last active September 1, 2015 01:16
Show Gist options
  • Select an option

  • Save andrewbranch/03fe7cb48ca1730e075f to your computer and use it in GitHub Desktop.

Select an option

Save andrewbranch/03fe7cb48ca1730e075f to your computer and use it in GitHub Desktop.

Revisions

  1. andrewbranch revised this gist Aug 31, 2015. 1 changed file with 3 additions and 6 deletions.
    9 changes: 3 additions & 6 deletions sort.js
    Original file line number Diff line number Diff line change
    @@ -15,9 +15,8 @@ function getTestPeople() {
    }

    function sort() {
    var args = Array.prototype.slice.call(arguments, 0);
    var lastArgument = args.splice(args.length - 1)[0];
    var sortFunctions = args; // args was mutated by splice
    var sortFunctions = Array.prototype.slice.call(arguments);
    var lastArgument = sortFunctions.pop();

    if (lastArgument.sort) {
    return lastArgument.sort(function(a, b) {
    @@ -31,11 +30,9 @@ function sort() {
    });
    }

    // Put the last guy back on, it wasn't an Array
    args.push(lastArgument);
    return sortFunctions.reduce(function(bound, arg) {
    return bound.bind(this, arg);
    }.bind(this), sort);
    }.bind(this), sort).bind(this, lastArgument);
    }

    function byName(a, b) {
  2. andrewbranch created this gist Aug 31, 2015.
    68 changes: 68 additions & 0 deletions sort.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,68 @@
    function getTestPeople() {
    return [{
    name: "Kylie",
    age: 18
    }, {
    name: "Andrew",
    age: 23
    }, {
    name: "Andrew",
    age: 18
    }, {
    name: "Clay",
    age: 23
    }];
    }

    function sort() {
    var args = Array.prototype.slice.call(arguments, 0);
    var lastArgument = args.splice(args.length - 1)[0];
    var sortFunctions = args; // args was mutated by splice

    if (lastArgument.sort) {
    return lastArgument.sort(function(a, b) {
    for (var i = 0; i < sortFunctions.length; i++) {
    var order = sortFunctions[i](a, b);
    if (order !== 0) {
    return order;
    }
    }
    return 0;
    });
    }

    // Put the last guy back on, it wasn't an Array
    args.push(lastArgument);
    return sortFunctions.reduce(function(bound, arg) {
    return bound.bind(this, arg);
    }.bind(this), sort);
    }

    function byName(a, b) {
    if (a.name > b.name) {
    return 1;
    } else if (a.name < b.name) {
    return -1;
    }
    return 0;
    }

    function byAge(a, b) {
    return a.age - b.age;
    }

    var sortByAgeThenName = sort(
    byAge,
    byName
    );

    var sortByNameThenAge = sort(
    byName,
    byAge
    );

    console.log('By Age Then Name');
    console.log(JSON.stringify(sortByAgeThenName(getTestPeople()), null, 2));

    console.log('By Name Then Age');
    console.log(JSON.stringify(sortByNameThenAge(getTestPeople()), null, 2));