Last active
September 1, 2015 01:16
-
-
Save andrewbranch/03fe7cb48ca1730e075f to your computer and use it in GitHub Desktop.
Revisions
-
andrewbranch revised this gist
Aug 31, 2015 . 1 changed file with 3 additions and 6 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -15,9 +15,8 @@ function getTestPeople() { } function sort() { 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() { }); } return sortFunctions.reduce(function(bound, arg) { return bound.bind(this, arg); }.bind(this), sort).bind(this, lastArgument); } function byName(a, b) { -
andrewbranch created this gist
Aug 31, 2015 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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));