Skip to content

Instantly share code, notes, and snippets.

@igstan
Created May 10, 2010 13:26
Show Gist options
  • Save igstan/396034 to your computer and use it in GitHub Desktop.
Save igstan/396034 to your computer and use it in GitHub Desktop.
Schwartzian transform in JavaScript
/**
* 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