JS.Comparable
Comparable is a module that helps you manipulate objects that can be ordered relative
to each other. It is designed to work exactly like Comparable in Ruby, only without the
nice method names like "<=" that Ruby allows. To use it, your class must define an
instance method called compareTo, that tells it how to compare itself to other
objects. As an example, let’s create a class to represent to-do list items. These can be
ordered according to their priority.
var TodoItem = new JS.Class({
include: JS.Comparable,
initialize: function(task, priority) {
this.task = task;
this.priority = priority;
},
// Must return -1 if this object is 'less than' other,
// +1 if it is 'greater than' other, or 0 if they are equal
compareTo: function(other) {
if (this.priority < other.priority) return -1;
if (this.priority > other.priority) return 1;
return 0;
}
});
TodoItem now has the following instance methods:
lt(other)– returnstrueiff the receiver is less thanotherlte(other)– returnstrueiff the receiver is less than or equal toothergt(other)– returnstrueiff the receiver is greater thanothergte(other)– returnstrueiff the receiver is greater than or equal toothereq(other)– returnstrueiff the receiver is equal tootherbetween(a,b)– returnstrueiff the receiver is betweenaandbinclusivecompareTo(other)– returns-1/0/1to indicate result of comparison
TodoItem also has a static method called compare that you should use for sorting.
Let’s create some items and see how they behave:
var items = [
new TodoItem('Go to work', 5),
new TodoItem('Buy milk', 3),
new TodoItem('Pay the rent', 2),
new TodoItem('Write code', 1),
new TodoItem('Head down the pub', 4)
];
items[2].lt(items[1]) // -> true
items[0].gte(items[3]) // -> true
items[4].eq(items[4]) // -> true
items[1].between(items[3], items[4]) // -> true
items.sort(TodoItem.compare)
// -> [
{task: 'Write code', ...},
{task: 'Pay the rent', ...},
{task: 'Buy milk', ...},
{task: 'Head down the pub', ...},
{task: 'Go to work', ...}
]