Skip to content

Instantly share code, notes, and snippets.

@josip
Created June 15, 2009 14:02
Show Gist options
  • Save josip/130124 to your computer and use it in GitHub Desktop.
Save josip/130124 to your computer and use it in GitHub Desktop.
// For use with MooTools
// Published under MIT license
window.Comparable = new Class({
// You class needs to implement "compareTo" method
// with same signature:
// compareTo: function (other) {
// if(this < other) return -1;
// if(this > other) return 1;
// return 0;
// },
lt: function (other) {
return this.compareTo(other) == -1;
},
lte: function (other) {
return this.compareTo(other) < 1;
},
gt: function (other) {
return this.compareTo(other) === 1;
},
gte: function (other) {
return this.compareTo(other) > -1;
},
eq: function (other) {
return this.compareTo(other) === 0;
},
between: function (a, b) {
return this.gte(a) && this.lte(b);
}
});
// Use with Array#sort()
Comparable.sortAscending = function (a, b) {
return a.compareTo(b);
};
Comparable.sortDescending = function (a, b) {
return b.compareTo(a);
};
// Or you can use this helper method
Comparable.sort = function (items, direction) {
direction = direction || "a";
return items.sort(direction.charAt(0) == "a" ? this.sortAscending : this.sortDescending);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment