getNiceTickValues.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.getTickValuesFixedDomain = exports.getTickValues = exports.getNiceTickValues = void 0;
  6. var _decimal = _interopRequireDefault(require("decimal.js-light"));
  7. var _utils = require("./util/utils");
  8. var _arithmetic = _interopRequireDefault(require("./util/arithmetic"));
  9. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10. function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
  11. function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  12. function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); }
  13. function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
  14. function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
  15. function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  16. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  17. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  18. function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
  19. function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
  20. /**
  21. * Calculate a interval of a minimum value and a maximum value
  22. *
  23. * @param {Number} min The minimum value
  24. * @param {Number} max The maximum value
  25. * @return {Array} An interval
  26. */
  27. function getValidInterval(_ref) {
  28. var _ref2 = _slicedToArray(_ref, 2),
  29. min = _ref2[0],
  30. max = _ref2[1];
  31. var validMin = min,
  32. validMax = max; // exchange
  33. if (min > max) {
  34. validMin = max;
  35. validMax = min;
  36. }
  37. return [validMin, validMax];
  38. }
  39. /**
  40. * Calculate the step which is easy to understand between ticks, like 10, 20, 25
  41. *
  42. * @param {Decimal} roughStep The rough step calculated by deviding the
  43. * difference by the tickCount
  44. * @param {Boolean} allowDecimals Allow the ticks to be decimals or not
  45. * @param {Integer} correctionFactor A correction factor
  46. * @return {Decimal} The step which is easy to understand between two ticks
  47. */
  48. function getFormatStep(roughStep, allowDecimals, correctionFactor) {
  49. if (roughStep.lte(0)) {
  50. return new _decimal.default(0);
  51. }
  52. var digitCount = _arithmetic.default.getDigitCount(roughStep.toNumber()); // The ratio between the rough step and the smallest number which has a bigger
  53. // order of magnitudes than the rough step
  54. var digitCountValue = new _decimal.default(10).pow(digitCount);
  55. var stepRatio = roughStep.div(digitCountValue); // When an integer and a float multiplied, the accuracy of result may be wrong
  56. var stepRatioScale = digitCount !== 1 ? 0.05 : 0.1;
  57. var amendStepRatio = new _decimal.default(Math.ceil(stepRatio.div(stepRatioScale).toNumber())).add(correctionFactor).mul(stepRatioScale);
  58. var formatStep = amendStepRatio.mul(digitCountValue);
  59. return allowDecimals ? formatStep : new _decimal.default(Math.ceil(formatStep));
  60. }
  61. /**
  62. * calculate the ticks when the minimum value equals to the maximum value
  63. *
  64. * @param {Number} value The minimum valuue which is also the maximum value
  65. * @param {Integer} tickCount The count of ticks
  66. * @param {Boolean} allowDecimals Allow the ticks to be decimals or not
  67. * @return {Array} ticks
  68. */
  69. function getTickOfSingleValue(value, tickCount, allowDecimals) {
  70. var step = 1; // calculate the middle value of ticks
  71. var middle = new _decimal.default(value);
  72. if (!middle.isint() && allowDecimals) {
  73. var absVal = Math.abs(value);
  74. if (absVal < 1) {
  75. // The step should be a float number when the difference is smaller than 1
  76. step = new _decimal.default(10).pow(_arithmetic.default.getDigitCount(value) - 1);
  77. middle = new _decimal.default(Math.floor(middle.div(step).toNumber())).mul(step);
  78. } else if (absVal > 1) {
  79. // Return the maximum integer which is smaller than 'value' when 'value' is greater than 1
  80. middle = new _decimal.default(Math.floor(value));
  81. }
  82. } else if (value === 0) {
  83. middle = new _decimal.default(Math.floor((tickCount - 1) / 2));
  84. } else if (!allowDecimals) {
  85. middle = new _decimal.default(Math.floor(value));
  86. }
  87. var middleIndex = Math.floor((tickCount - 1) / 2);
  88. var fn = (0, _utils.compose)((0, _utils.map)(function (n) {
  89. return middle.add(new _decimal.default(n - middleIndex).mul(step)).toNumber();
  90. }), _utils.range);
  91. return fn(0, tickCount);
  92. }
  93. /**
  94. * Calculate the step
  95. *
  96. * @param {Number} min The minimum value of an interval
  97. * @param {Number} max The maximum value of an interval
  98. * @param {Integer} tickCount The count of ticks
  99. * @param {Boolean} allowDecimals Allow the ticks to be decimals or not
  100. * @param {Number} correctionFactor A correction factor
  101. * @return {Object} The step, minimum value of ticks, maximum value of ticks
  102. */
  103. function calculateStep(min, max, tickCount, allowDecimals) {
  104. var correctionFactor = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  105. // dirty hack (for recharts' test)
  106. if (!Number.isFinite((max - min) / (tickCount - 1))) {
  107. return {
  108. step: new _decimal.default(0),
  109. tickMin: new _decimal.default(0),
  110. tickMax: new _decimal.default(0)
  111. };
  112. } // The step which is easy to understand between two ticks
  113. var step = getFormatStep(new _decimal.default(max).sub(min).div(tickCount - 1), allowDecimals, correctionFactor); // A medial value of ticks
  114. var middle; // When 0 is inside the interval, 0 should be a tick
  115. if (min <= 0 && max >= 0) {
  116. middle = new _decimal.default(0);
  117. } else {
  118. // calculate the middle value
  119. middle = new _decimal.default(min).add(max).div(2); // minus modulo value
  120. middle = middle.sub(new _decimal.default(middle).mod(step));
  121. }
  122. var belowCount = Math.ceil(middle.sub(min).div(step).toNumber());
  123. var upCount = Math.ceil(new _decimal.default(max).sub(middle).div(step).toNumber());
  124. var scaleCount = belowCount + upCount + 1;
  125. if (scaleCount > tickCount) {
  126. // When more ticks need to cover the interval, step should be bigger.
  127. return calculateStep(min, max, tickCount, allowDecimals, correctionFactor + 1);
  128. }
  129. if (scaleCount < tickCount) {
  130. // When less ticks can cover the interval, we should add some additional ticks
  131. upCount = max > 0 ? upCount + (tickCount - scaleCount) : upCount;
  132. belowCount = max > 0 ? belowCount : belowCount + (tickCount - scaleCount);
  133. }
  134. return {
  135. step: step,
  136. tickMin: middle.sub(new _decimal.default(belowCount).mul(step)),
  137. tickMax: middle.add(new _decimal.default(upCount).mul(step))
  138. };
  139. }
  140. /**
  141. * Calculate the ticks of an interval, the count of ticks will be guraranteed
  142. *
  143. * @param {Number} min, max min: The minimum value, max: The maximum value
  144. * @param {Integer} tickCount The count of ticks
  145. * @param {Boolean} allowDecimals Allow the ticks to be decimals or not
  146. * @return {Array} ticks
  147. */
  148. function getNiceTickValuesFn(_ref3) {
  149. var _ref4 = _slicedToArray(_ref3, 2),
  150. min = _ref4[0],
  151. max = _ref4[1];
  152. var tickCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 6;
  153. var allowDecimals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  154. // More than two ticks should be return
  155. var count = Math.max(tickCount, 2);
  156. var _getValidInterval = getValidInterval([min, max]),
  157. _getValidInterval2 = _slicedToArray(_getValidInterval, 2),
  158. cormin = _getValidInterval2[0],
  159. cormax = _getValidInterval2[1];
  160. if (cormin === -Infinity || cormax === Infinity) {
  161. var _values = cormax === Infinity ? [cormin].concat(_toConsumableArray((0, _utils.range)(0, tickCount - 1).map(function () {
  162. return Infinity;
  163. }))) : [].concat(_toConsumableArray((0, _utils.range)(0, tickCount - 1).map(function () {
  164. return -Infinity;
  165. })), [cormax]);
  166. return min > max ? (0, _utils.reverse)(_values) : _values;
  167. }
  168. if (cormin === cormax) {
  169. return getTickOfSingleValue(cormin, tickCount, allowDecimals);
  170. } // Get the step between two ticks
  171. var _calculateStep = calculateStep(cormin, cormax, count, allowDecimals),
  172. step = _calculateStep.step,
  173. tickMin = _calculateStep.tickMin,
  174. tickMax = _calculateStep.tickMax;
  175. var values = _arithmetic.default.rangeStep(tickMin, tickMax.add(new _decimal.default(0.1).mul(step)), step);
  176. return min > max ? (0, _utils.reverse)(values) : values;
  177. }
  178. /**
  179. * Calculate the ticks of an interval, the count of ticks won't be guraranteed
  180. *
  181. * @param {Number} min, max min: The minimum value, max: The maximum value
  182. * @param {Integer} tickCount The count of ticks
  183. * @param {Boolean} allowDecimals Allow the ticks to be decimals or not
  184. * @return {Array} ticks
  185. */
  186. function getTickValuesFn(_ref5) {
  187. var _ref6 = _slicedToArray(_ref5, 2),
  188. min = _ref6[0],
  189. max = _ref6[1];
  190. var tickCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 6;
  191. var allowDecimals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  192. // More than two ticks should be return
  193. var count = Math.max(tickCount, 2);
  194. var _getValidInterval3 = getValidInterval([min, max]),
  195. _getValidInterval4 = _slicedToArray(_getValidInterval3, 2),
  196. cormin = _getValidInterval4[0],
  197. cormax = _getValidInterval4[1];
  198. if (cormin === -Infinity || cormax === Infinity) {
  199. return [min, max];
  200. }
  201. if (cormin === cormax) {
  202. return getTickOfSingleValue(cormin, tickCount, allowDecimals);
  203. }
  204. var step = getFormatStep(new _decimal.default(cormax).sub(cormin).div(count - 1), allowDecimals, 0);
  205. var fn = (0, _utils.compose)((0, _utils.map)(function (n) {
  206. return new _decimal.default(cormin).add(new _decimal.default(n).mul(step)).toNumber();
  207. }), _utils.range);
  208. var values = fn(0, count).filter(function (entry) {
  209. return entry >= cormin && entry <= cormax;
  210. });
  211. return min > max ? (0, _utils.reverse)(values) : values;
  212. }
  213. /**
  214. * Calculate the ticks of an interval, the count of ticks won't be guraranteed,
  215. * but the domain will be guaranteed
  216. *
  217. * @param {Number} min, max min: The minimum value, max: The maximum value
  218. * @param {Integer} tickCount The count of ticks
  219. * @param {Boolean} allowDecimals Allow the ticks to be decimals or not
  220. * @return {Array} ticks
  221. */
  222. function getTickValuesFixedDomainFn(_ref7, tickCount) {
  223. var _ref8 = _slicedToArray(_ref7, 2),
  224. min = _ref8[0],
  225. max = _ref8[1];
  226. var allowDecimals = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  227. // More than two ticks should be return
  228. var _getValidInterval5 = getValidInterval([min, max]),
  229. _getValidInterval6 = _slicedToArray(_getValidInterval5, 2),
  230. cormin = _getValidInterval6[0],
  231. cormax = _getValidInterval6[1];
  232. if (cormin === -Infinity || cormax === Infinity) {
  233. return [min, max];
  234. }
  235. if (cormin === cormax) {
  236. return [cormin];
  237. }
  238. var count = Math.max(tickCount, 2);
  239. var step = getFormatStep(new _decimal.default(cormax).sub(cormin).div(count - 1), allowDecimals, 0);
  240. var values = [].concat(_toConsumableArray(_arithmetic.default.rangeStep(new _decimal.default(cormin), new _decimal.default(cormax).sub(new _decimal.default(0.99).mul(step)), step)), [cormax]);
  241. return min > max ? (0, _utils.reverse)(values) : values;
  242. }
  243. var getNiceTickValues = (0, _utils.memoize)(getNiceTickValuesFn);
  244. exports.getNiceTickValues = getNiceTickValues;
  245. var getTickValues = (0, _utils.memoize)(getTickValuesFn);
  246. exports.getTickValues = getTickValues;
  247. var getTickValuesFixedDomain = (0, _utils.memoize)(getTickValuesFixedDomainFn);
  248. exports.getTickValuesFixedDomain = getTickValuesFixedDomain;