封装比较大小的函数

* ./utils/Comparator.js

/**
 * Created by Mch on 8/18/18.
 */
function Comparator(comparefunction) {
    this.compare = comparefunction || Comparator.defaultCompareFunction;
}

Comparator.defaultCompareFunction = function(a, b) {
    if (a===b) {
	return 0;
    }
    return a < b ? -1 : 1;
};

Comparator.prototype.equal = function(a, b) {
    return this.compare(a, b) === 0;
};

Comparator.prototype.lessThan = function(a, b) {
    return this.compare(a, b) < 0;
};

Comparator.prototype.greaterThan = function(a, b) {
    return this.compare(a, b) > 0;
};

Comparator.prototype.lessThanOrEqual = function(a, b) {
    return this.lessThan(a, b) || this.equal(a, b);
};

Comparator.prototype.greaterThanOrEqual = function(a, b) {
    return this.greaterThan(a, b) || this.equal(a, b);
};

Comparator.prototype.reverse = function() {
    const compareOriginal = this.compare;
    this.compare = function (a, b) {
	return compareOriginal(b, a)
    }
};

module.exports = Comparator;

test:

/**
 * Created by Mch on 8/19/18.
 */
var Comparator = require('./utils/Comparator');
// console.log(Comparator);

var comparator = new Comparator(function(a, b) {
    return a.localeCompare(b);
});
console.log(comparator.equal('Hello', 'Hello'));  // true
console.log(comparator.greaterThanOrEqual('World', 'Hello')); // true
console.log(comparator.lessThanOrEqual('world', 'hello')); // false

Run:

$ node compare.js
true
true
false