Created
May 17, 2017 14:52
-
-
Save loretoparisi/190ce1cdc85d6b0d766b868f4a60d7d3 to your computer and use it in GitHub Desktop.
Schwartzian Sort Transform
This file contains 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 characters
/** | |
* Schwartzian Sort Transform | |
* @param array Array | |
* @param f function | |
* @param asc bool To sort ascending, false to sort descending | |
* @example arr = schwartzianSort(arr, function(o) { return o.date }, false) | |
*/ | |
var schwartzianSort = function(array,f,asc) { | |
for (var i=array.length;i;){ | |
var o = array[--i]; | |
array[i] = [].concat(f.call(o,o,i),o); | |
} | |
array.sort(function(a,b){ | |
for (var i=0,len=a.length;i<len;++i){ | |
if (a[i]!=b[i]) return a[i]<b[i]?asc?-1:1:1; | |
} | |
return 0; | |
}); | |
for (var i=array.length;i;){ | |
array[--i]=array[i][array[i].length-1]; | |
} | |
return array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment