Created
May 10, 2010 13:26
-
-
Save igstan/396034 to your computer and use it in GitHub Desktop.
Schwartzian transform in JavaScript
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 characters
/** | |
* See http://en.wikipedia.org/wiki/Schwartzian_transform | |
* | |
* @author Ionut G. Stan - http://igstan.ro | |
* @license BSD License | |
*/ | |
var schwartzianSort = (function () { | |
var decorate = function (sortKey) { | |
return function (item) { | |
return [item[sortKey](), item]; | |
}; | |
}; | |
var compare = function (sortFunction) { | |
sortFunction = sortFunction || defaultSortFunction; | |
return function (a, b) { | |
return sortFunction(a[0], b[0]); | |
}; | |
}; | |
var defaultSortFunction = function (a, b) { | |
if (a < b) return -1; | |
if (a > b) return 1; | |
return 0; | |
}; | |
var undecorate = function (item) { | |
return item[1]; | |
}; | |
return function (items, sortKey, sortFunction) { | |
return items.map(decorate(sortKey)) | |
.sort(compare(sortFunction)) | |
.map(undecorate); | |
}; | |
})(); | |
// var puts = require("sys").puts; | |
// | |
// var modificationTimeComputed = 0; | |
// | |
// var proto = { | |
// modificationTime : function () { | |
// modificationTimeComputed++; | |
// return this.time; | |
// }, | |
// | |
// toString : function () { | |
// return this.time; | |
// } | |
// }; | |
// | |
// | |
// var a = Object.create(proto); | |
// a.time = "2010-05-01"; | |
// | |
// var b = Object.create(proto); | |
// b.time = "2010-05-02"; | |
// | |
// var c = Object.create(proto); | |
// c.time = "2010-05-03"; | |
// | |
// var d = Object.create(proto); | |
// d.time = "2010-05-04"; | |
// | |
// var e = Object.create(proto); | |
// e.time = "2010-05-05"; | |
// | |
// | |
// var objs = [b, d, e, a, c]; | |
// | |
// objs = schwartzianSort(objs, "modificationTime"); | |
// | |
// | |
// puts("modificationTimeComputed: " + modificationTimeComputed) | |
// puts(objs); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment