forked from trekhleb/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComparator.js
More file actions
46 lines (38 loc) · 888 Bytes
/
Comparator.js
File metadata and controls
46 lines (38 loc) · 888 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
export default class Comparator {
/**
* @param {function(a: *, b: *)} [compareFunction]
*/
constructor(compareFunction) {
this.compare = compareFunction || Comparator.defaultCompareFunction;
}
/**
* @param {(string|number)} a
* @param {(string|number)} b
* @returns {number}
*/
static defaultCompareFunction(a, b) {
if (a === b) {
return 0;
}
return a < b ? -1 : 1;
}
equal(a, b) {
return this.compare(a, b) === 0;
}
lessThan(a, b) {
return this.compare(a, b) < 0;
}
greaterThan(a, b) {
return this.compare(a, b) > 0;
}
lessThanOrEqual(a, b) {
return this.lessThan(a, b) || this.equal(a, b);
}
greaterThanOrEqual(a, b) {
return this.greaterThan(a, b) || this.equal(a, b);
}
reverse() {
const compareOriginal = this.compare;
this.compare = (a, b) => compareOriginal(b, a);
}
}