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.
// In the browser JS.require('JS.Comparable', function(Comparable) { ... }); // In CommonJS var Comparable = require('jsclass/src/comparable').Comparable;
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 Class({ include: 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)
– returnstrue
iff the receiver is less thanother
lte(other)
– returnstrue
iff the receiver is less than or equal toother
gt(other)
– returnstrue
iff the receiver is greater thanother
gte(other)
– returnstrue
iff the receiver is greater than or equal toother
eq(other)
– returnstrue
iff the receiver is equal toother
between(a,b)
– returnstrue
iff the receiver is betweena
andb
inclusivecompareTo(other)
– returns-1
/0
/1
to indicate result of comparison
TodoItem
also has a class 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', ...} // ]