-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
97 lines (82 loc) · 1.6 KB
/
index.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
class Bounds {
static mixin(obj) {
for (const key in Bounds.prototype) {
obj[key] = Bounds.prototype[key];
}
return obj;
}
compare(fn) {
this._compare = fn;
return this;
}
distance(fn) {
this._distance = fn;
return this;
}
min(v) {
if (!arguments.length) {
return this._min;
}
this._min = v;
delete this._reversed;
return this;
}
max(v) {
if (!arguments.length) {
return this._max;
}
this._max = v;
delete this._reversed;
return this;
}
before(v) {
return this._min && (this._compare(v, this._min) < 0);
}
after(v) {
return this._max && (this._compare(v, this._max) > 0);
}
out(v) {
return this.before(v) || this.after(v);
}
in(v) {
return !this.out(v);
}
valid(v) {
if (this.reversed()) {
return !this.after(v) || !this.before(v);
}
return this.in(v);
}
invalid(v) {
return !this.valid(v);
}
reversed() {
if (this._reversed === undefined) {
this._reversed = calculateReversed(this);
}
return this._reversed;
}
restrict(v) {
const { _min, _max } = this;
if (this.reversed()) {
if (this.after(v) && this.before(v)) {
// select closer bound
return (this._distance(_max, v) < this._distance(v, _min)) ?
_max :
_min;
}
return v;
}
if (this.before(v)) {
return _min;
}
if (this.after(v)) {
return _max;
}
return v;
}
}
function calculateReversed(self) {
return self._min && self._max && self.before(self._max);
}
module.exports = Bounds;