-
Notifications
You must be signed in to change notification settings - Fork 411
Comparator
Felipe Ribeiro edited this page Feb 19, 2014
·
2 revisions
The Comparator object is used in many data structures and algorithms that involve comparison and sorting of elements.
It can be created from a comparator function that has to attend to this requirements:
- The function receives two parameters (a and b) that should be compared.
- If the elements are equal, the function should return 0
- If the first parameter (a) is lower than the second(b) return a number < 0
- If the first parameter (a) is greater than the second return a number > 0
If no comparator function is passed to the Comparator object, it will use a default implementation that reproduces the behavior of the native comparison operators: >, < and ==.
function defaultComparator(a, b) {
if (a == b) return 0;
return a < b ? -1 : 1;
}
The Comparator Object just provides syntactic sugar for the comparator function.
Code: https://github.com/felipernb/algorithms.js/blob/master/util/comparator.js
/**
* Initialize the comparator object with a compare function
*
* If the function is not passed, it will use the default
* compare signs (<, > and ==)
*
* @param Function
*/
function Comparator(compareFn) {
if (compareFn) {
this.compare = compareFn;
}
}
/**
* Default implementation for the compare function
*/
Comparator.prototype.compare = function (a, b) {
if (a == b) return 0;
return a < b ? -1 : 1;
};
Comparator.prototype.lessThan = function (a, b) {
return this.compare(a, b) < 0;
};
Comparator.prototype.lessThanOrEqual = function (a, b) {
return this.lessThan(a, b) || a == b;
};
Comparator.prototype.greaterThan = function (a, b) {
return this.compare(a, b) > 0;
};
Comparator.prototype.greaterThanOrEqual = function (a, b) {
return this.greaterThan(a, b) || a == b;
};