vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.1 KiB

  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. * Adjust the range so that the passed value fits in it.
  16. *
  17. * If the value is outside of the current extremes, adjust
  18. * the min or max so that the value is within the range.
  19. *
  20. * @param {number} value Numeric value to fit in range
  21. */
  22. Range.prototype.adjust = function(value) {
  23. if (value === undefined) return;
  24. if (this.min === undefined || this.min > value ) {
  25. this.min = value;
  26. }
  27. if (this.max === undefined || this.max < value) {
  28. this.max = value;
  29. }
  30. };
  31. /**
  32. * Adjust the current range so that the passed range fits in it.
  33. *
  34. * @param {Range} range Range instance to fit in current instance
  35. */
  36. Range.prototype.combine = function(range) {
  37. this.add(range.min);
  38. this.add(range.max);
  39. };
  40. /**
  41. * Expand the range by the given value
  42. *
  43. * min will be lowered by given value;
  44. * max will be raised by given value
  45. *
  46. * Shrinking by passing a negative value is allowed.
  47. *
  48. * @param {number} val Amount by which to expand or shrink current range with
  49. */
  50. Range.prototype.expand = function(val) {
  51. if (val === undefined) {
  52. return;
  53. }
  54. var newMin = this.min - val;
  55. var newMax = this.max + val;
  56. // Note that following allows newMin === newMax.
  57. // This should be OK, since method expand() allows this also.
  58. if (newMin > newMax) {
  59. throw new Error('Passed expansion value makes range invalid');
  60. }
  61. this.min = newMin;
  62. this.max = newMax;
  63. };
  64. /**
  65. * Determine the full range width of current instance.
  66. *
  67. * @returns {num} The calculated width of this range
  68. */
  69. Range.prototype.range = function() {
  70. return this.max - this.min;
  71. };
  72. /**
  73. * Determine the central point of current instance.
  74. *
  75. * @returns {number} the value in the middle of min and max
  76. */
  77. Range.prototype.center = function() {
  78. return (this.min + this.max) / 2;
  79. };
  80. module.exports = Range;