1 | /**
|
2 | * @prototype Range
|
3 | *
|
4 | * Helper class to make working with related min and max values easier.
|
5 | *
|
6 | * The range is inclusive; a given value is considered part of the range if:
|
7 | *
|
8 | * this.min <= value <= this.max
|
9 | */
|
10 | function Range() {
|
11 | this.min = undefined;
|
12 | this.max = undefined;
|
13 | }
|
14 |
|
15 |
|
16 | /**
|
17 | * Adjust the range so that the passed value fits in it.
|
18 | *
|
19 | * If the value is outside of the current extremes, adjust
|
20 | * the min or max so that the value is within the range.
|
21 | *
|
22 | * @param {number} value Numeric value to fit in range
|
23 | */
|
24 | Range.prototype.adjust = function(value) {
|
25 | if (value === undefined) return;
|
26 |
|
27 | if (this.min === undefined || this.min > value ) {
|
28 | this.min = value;
|
29 | }
|
30 |
|
31 | if (this.max === undefined || this.max < value) {
|
32 | this.max = value;
|
33 | }
|
34 | };
|
35 |
|
36 |
|
37 | /**
|
38 | * Adjust the current range so that the passed range fits in it.
|
39 | *
|
40 | * @param {Range} range Range instance to fit in current instance
|
41 | */
|
42 | Range.prototype.combine = function(range) {
|
43 | this.add(range.min);
|
44 | this.add(range.max);
|
45 | };
|
46 |
|
47 |
|
48 | /**
|
49 | * Expand the range by the given value
|
50 | *
|
51 | * min will be lowered by given value;
|
52 | * max will be raised by given value
|
53 | *
|
54 | * Shrinking by passing a negative value is allowed.
|
55 | *
|
56 | * @param {number} val Amount by which to expand or shrink current range with
|
57 | */
|
58 | Range.prototype.expand = function(val) {
|
59 | if (val === undefined) {
|
60 | return;
|
61 | }
|
62 |
|
63 | var newMin = this.min - val;
|
64 | var newMax = this.max + val;
|
65 |
|
66 | // Note that following allows newMin === newMax.
|
67 | // This should be OK, since method expand() allows this also.
|
68 | if (newMin > newMax) {
|
69 | throw new Error('Passed expansion value makes range invalid');
|
70 | }
|
71 |
|
72 | this.min = newMin;
|
73 | this.max = newMax;
|
74 | };
|
75 |
|
76 |
|
77 | /**
|
78 | * Determine the full range width of current instance.
|
79 | *
|
80 | * @returns {num} The calculated width of this range
|
81 | */
|
82 | Range.prototype.range = function() {
|
83 | return this.max - this.min;
|
84 | };
|
85 |
|
86 |
|
87 | /**
|
88 | * Determine the central point of current instance.
|
89 | *
|
90 | * @returns {number} the value in the middle of min and max
|
91 | */
|
92 | Range.prototype.center = function() {
|
93 | return (this.min + this.max) / 2;
|
94 | };
|
95 |
|
96 |
|
97 | module.exports = Range;
|