number.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. var zrUtil = require("zrender/lib/core/util");
  2. var RADIAN_EPSILON = 1e-4;
  3. function _trim(str) {
  4. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  5. }
  6. /**
  7. * Linear mapping a value from domain to range
  8. * @memberOf module:echarts/util/number
  9. * @param {(number|Array.<number>)} val
  10. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  11. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  12. * @param {boolean} clamp
  13. * @return {(number|Array.<number>}
  14. */
  15. function linearMap(val, domain, range, clamp) {
  16. var subDomain = domain[1] - domain[0];
  17. var subRange = range[1] - range[0];
  18. if (subDomain === 0) {
  19. return subRange === 0 ? range[0] : (range[0] + range[1]) / 2;
  20. } // Avoid accuracy problem in edge, such as
  21. // 146.39 - 62.83 === 83.55999999999999.
  22. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  23. // It is a little verbose for efficiency considering this method
  24. // is a hotspot.
  25. if (clamp) {
  26. if (subDomain > 0) {
  27. if (val <= domain[0]) {
  28. return range[0];
  29. } else if (val >= domain[1]) {
  30. return range[1];
  31. }
  32. } else {
  33. if (val >= domain[0]) {
  34. return range[0];
  35. } else if (val <= domain[1]) {
  36. return range[1];
  37. }
  38. }
  39. } else {
  40. if (val === domain[0]) {
  41. return range[0];
  42. }
  43. if (val === domain[1]) {
  44. return range[1];
  45. }
  46. }
  47. return (val - domain[0]) / subDomain * subRange + range[0];
  48. }
  49. /**
  50. * Convert a percent string to absolute number.
  51. * Returns NaN if percent is not a valid string or number
  52. * @memberOf module:echarts/util/number
  53. * @param {string|number} percent
  54. * @param {number} all
  55. * @return {number}
  56. */
  57. function parsePercent(percent, all) {
  58. switch (percent) {
  59. case 'center':
  60. case 'middle':
  61. percent = '50%';
  62. break;
  63. case 'left':
  64. case 'top':
  65. percent = '0%';
  66. break;
  67. case 'right':
  68. case 'bottom':
  69. percent = '100%';
  70. break;
  71. }
  72. if (typeof percent === 'string') {
  73. if (_trim(percent).match(/%$/)) {
  74. return parseFloat(percent) / 100 * all;
  75. }
  76. return parseFloat(percent);
  77. }
  78. return percent == null ? NaN : +percent;
  79. }
  80. /**
  81. * (1) Fix rounding error of float numbers.
  82. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  83. *
  84. * @param {number} x
  85. * @param {number} [precision]
  86. * @param {boolean} [returnStr]
  87. * @return {number|string}
  88. */
  89. function round(x, precision, returnStr) {
  90. if (precision == null) {
  91. precision = 10;
  92. } // Avoid range error
  93. precision = Math.min(Math.max(0, precision), 20);
  94. x = (+x).toFixed(precision);
  95. return returnStr ? x : +x;
  96. }
  97. function asc(arr) {
  98. arr.sort(function (a, b) {
  99. return a - b;
  100. });
  101. return arr;
  102. }
  103. /**
  104. * Get precision
  105. * @param {number} val
  106. */
  107. function getPrecision(val) {
  108. val = +val;
  109. if (isNaN(val)) {
  110. return 0;
  111. } // It is much faster than methods converting number to string as follows
  112. // var tmp = val.toString();
  113. // return tmp.length - 1 - tmp.indexOf('.');
  114. // especially when precision is low
  115. var e = 1;
  116. var count = 0;
  117. while (Math.round(val * e) / e !== val) {
  118. e *= 10;
  119. count++;
  120. }
  121. return count;
  122. }
  123. /**
  124. * @param {string|number} val
  125. * @return {number}
  126. */
  127. function getPrecisionSafe(val) {
  128. var str = val.toString(); // Consider scientific notation: '3.4e-12' '3.4e+12'
  129. var eIndex = str.indexOf('e');
  130. if (eIndex > 0) {
  131. var precision = +str.slice(eIndex + 1);
  132. return precision < 0 ? -precision : 0;
  133. } else {
  134. var dotIndex = str.indexOf('.');
  135. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  136. }
  137. }
  138. /**
  139. * Minimal dicernible data precisioin according to a single pixel.
  140. *
  141. * @param {Array.<number>} dataExtent
  142. * @param {Array.<number>} pixelExtent
  143. * @return {number} precision
  144. */
  145. function getPixelPrecision(dataExtent, pixelExtent) {
  146. var log = Math.log;
  147. var LN10 = Math.LN10;
  148. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  149. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20.
  150. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  151. return !isFinite(precision) ? 20 : precision;
  152. }
  153. /**
  154. * Get a data of given precision, assuring the sum of percentages
  155. * in valueList is 1.
  156. * The largest remainer method is used.
  157. * https://en.wikipedia.org/wiki/Largest_remainder_method
  158. *
  159. * @param {Array.<number>} valueList a list of all data
  160. * @param {number} idx index of the data to be processed in valueList
  161. * @param {number} precision integer number showing digits of precision
  162. * @return {number} percent ranging from 0 to 100
  163. */
  164. function getPercentWithPrecision(valueList, idx, precision) {
  165. if (!valueList[idx]) {
  166. return 0;
  167. }
  168. var sum = zrUtil.reduce(valueList, function (acc, val) {
  169. return acc + (isNaN(val) ? 0 : val);
  170. }, 0);
  171. if (sum === 0) {
  172. return 0;
  173. }
  174. var digits = Math.pow(10, precision);
  175. var votesPerQuota = zrUtil.map(valueList, function (val) {
  176. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  177. });
  178. var targetSeats = digits * 100;
  179. var seats = zrUtil.map(votesPerQuota, function (votes) {
  180. // Assign automatic seats.
  181. return Math.floor(votes);
  182. });
  183. var currentSum = zrUtil.reduce(seats, function (acc, val) {
  184. return acc + val;
  185. }, 0);
  186. var remainder = zrUtil.map(votesPerQuota, function (votes, idx) {
  187. return votes - seats[idx];
  188. }); // Has remainding votes.
  189. while (currentSum < targetSeats) {
  190. // Find next largest remainder.
  191. var max = Number.NEGATIVE_INFINITY;
  192. var maxId = null;
  193. for (var i = 0, len = remainder.length; i < len; ++i) {
  194. if (remainder[i] > max) {
  195. max = remainder[i];
  196. maxId = i;
  197. }
  198. } // Add a vote to max remainder.
  199. ++seats[maxId];
  200. remainder[maxId] = 0;
  201. ++currentSum;
  202. }
  203. return seats[idx] / digits;
  204. } // Number.MAX_SAFE_INTEGER, ie do not support.
  205. var MAX_SAFE_INTEGER = 9007199254740991;
  206. /**
  207. * To 0 - 2 * PI, considering negative radian.
  208. * @param {number} radian
  209. * @return {number}
  210. */
  211. function remRadian(radian) {
  212. var pi2 = Math.PI * 2;
  213. return (radian % pi2 + pi2) % pi2;
  214. }
  215. /**
  216. * @param {type} radian
  217. * @return {boolean}
  218. */
  219. function isRadianAroundZero(val) {
  220. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  221. }
  222. var TIME_REG = /^(?:(\d{4})(?:[-\/](\d{1,2})(?:[-\/](\d{1,2})(?:[T ](\d{1,2})(?::(\d\d)(?::(\d\d)(?:[.,](\d+))?)?)?(Z|[\+\-]\d\d:?\d\d)?)?)?)?)?$/; // jshint ignore:line
  223. /**
  224. * @param {string|Date|number} value These values can be accepted:
  225. * + An instance of Date, represent a time in its own time zone.
  226. * + Or string in a subset of ISO 8601, only including:
  227. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  228. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  229. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  230. * all of which will be treated as local time if time zone is not specified
  231. * (see <https://momentjs.com/>).
  232. * + Or other string format, including (all of which will be treated as loacal time):
  233. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  234. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  235. * + a timestamp, which represent a time in UTC.
  236. * @return {Date} date
  237. */
  238. function parseDate(value) {
  239. if (value instanceof Date) {
  240. return value;
  241. } else if (typeof value === 'string') {
  242. // Different browsers parse date in different way, so we parse it manually.
  243. // Some other issues:
  244. // new Date('1970-01-01') is UTC,
  245. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  246. // See issue #3623
  247. var match = TIME_REG.exec(value);
  248. if (!match) {
  249. // return Invalid Date.
  250. return new Date(NaN);
  251. } // Use local time when no timezone offset specifed.
  252. if (!match[8]) {
  253. // match[n] can only be string or undefined.
  254. // But take care of '12' + 1 => '121'.
  255. return new Date(+match[1], +(match[2] || 1) - 1, +match[3] || 1, +match[4] || 0, +(match[5] || 0), +match[6] || 0, +match[7] || 0);
  256. } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  257. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  258. // For example, system timezone is set as "Time Zone: America/Toronto",
  259. // then these code will get different result:
  260. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  261. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  262. // So we should not use `new Date`, but use `Date.UTC`.
  263. else {
  264. var hour = +match[4] || 0;
  265. if (match[8].toUpperCase() !== 'Z') {
  266. hour -= match[8].slice(0, 3);
  267. }
  268. return new Date(Date.UTC(+match[1], +(match[2] || 1) - 1, +match[3] || 1, hour, +(match[5] || 0), +match[6] || 0, +match[7] || 0));
  269. }
  270. } else if (value == null) {
  271. return new Date(NaN);
  272. }
  273. return new Date(Math.round(value));
  274. }
  275. /**
  276. * Quantity of a number. e.g. 0.1, 1, 10, 100
  277. *
  278. * @param {number} val
  279. * @return {number}
  280. */
  281. function quantity(val) {
  282. return Math.pow(10, quantityExponent(val));
  283. }
  284. function quantityExponent(val) {
  285. return Math.floor(Math.log(val) / Math.LN10);
  286. }
  287. /**
  288. * find a “nice” number approximately equal to x. Round the number if round = true,
  289. * take ceiling if round = false. The primary observation is that the “nicest”
  290. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  291. *
  292. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  293. *
  294. * @param {number} val Non-negative value.
  295. * @param {boolean} round
  296. * @return {number}
  297. */
  298. function nice(val, round) {
  299. var exponent = quantityExponent(val);
  300. var exp10 = Math.pow(10, exponent);
  301. var f = val / exp10; // 1 <= f < 10
  302. var nf;
  303. if (round) {
  304. if (f < 1.5) {
  305. nf = 1;
  306. } else if (f < 2.5) {
  307. nf = 2;
  308. } else if (f < 4) {
  309. nf = 3;
  310. } else if (f < 7) {
  311. nf = 5;
  312. } else {
  313. nf = 10;
  314. }
  315. } else {
  316. if (f < 1) {
  317. nf = 1;
  318. } else if (f < 2) {
  319. nf = 2;
  320. } else if (f < 3) {
  321. nf = 3;
  322. } else if (f < 5) {
  323. nf = 5;
  324. } else {
  325. nf = 10;
  326. }
  327. }
  328. val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  329. // 20 is the uppper bound of toFixed.
  330. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  331. }
  332. /**
  333. * Order intervals asc, and split them when overlap.
  334. * expect(numberUtil.reformIntervals([
  335. * {interval: [18, 62], close: [1, 1]},
  336. * {interval: [-Infinity, -70], close: [0, 0]},
  337. * {interval: [-70, -26], close: [1, 1]},
  338. * {interval: [-26, 18], close: [1, 1]},
  339. * {interval: [62, 150], close: [1, 1]},
  340. * {interval: [106, 150], close: [1, 1]},
  341. * {interval: [150, Infinity], close: [0, 0]}
  342. * ])).toEqual([
  343. * {interval: [-Infinity, -70], close: [0, 0]},
  344. * {interval: [-70, -26], close: [1, 1]},
  345. * {interval: [-26, 18], close: [0, 1]},
  346. * {interval: [18, 62], close: [0, 1]},
  347. * {interval: [62, 150], close: [0, 1]},
  348. * {interval: [150, Infinity], close: [0, 0]}
  349. * ]);
  350. * @param {Array.<Object>} list, where `close` mean open or close
  351. * of the interval, and Infinity can be used.
  352. * @return {Array.<Object>} The origin list, which has been reformed.
  353. */
  354. function reformIntervals(list) {
  355. list.sort(function (a, b) {
  356. return littleThan(a, b, 0) ? -1 : 1;
  357. });
  358. var curr = -Infinity;
  359. var currClose = 1;
  360. for (var i = 0; i < list.length;) {
  361. var interval = list[i].interval;
  362. var close = list[i].close;
  363. for (var lg = 0; lg < 2; lg++) {
  364. if (interval[lg] <= curr) {
  365. interval[lg] = curr;
  366. close[lg] = !lg ? 1 - currClose : 1;
  367. }
  368. curr = interval[lg];
  369. currClose = close[lg];
  370. }
  371. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  372. list.splice(i, 1);
  373. } else {
  374. i++;
  375. }
  376. }
  377. return list;
  378. function littleThan(a, b, lg) {
  379. return a.interval[lg] < b.interval[lg] || a.interval[lg] === b.interval[lg] && (a.close[lg] - b.close[lg] === (!lg ? 1 : -1) || !lg && littleThan(a, b, 1));
  380. }
  381. }
  382. /**
  383. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  384. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  385. * subtraction forces infinities to NaN
  386. *
  387. * @param {*} v
  388. * @return {boolean}
  389. */
  390. function isNumeric(v) {
  391. return v - parseFloat(v) >= 0;
  392. }
  393. exports.linearMap = linearMap;
  394. exports.parsePercent = parsePercent;
  395. exports.round = round;
  396. exports.asc = asc;
  397. exports.getPrecision = getPrecision;
  398. exports.getPrecisionSafe = getPrecisionSafe;
  399. exports.getPixelPrecision = getPixelPrecision;
  400. exports.getPercentWithPrecision = getPercentWithPrecision;
  401. exports.MAX_SAFE_INTEGER = MAX_SAFE_INTEGER;
  402. exports.remRadian = remRadian;
  403. exports.isRadianAroundZero = isRadianAroundZero;
  404. exports.parseDate = parseDate;
  405. exports.quantity = quantity;
  406. exports.nice = nice;
  407. exports.reformIntervals = reformIntervals;
  408. exports.isNumeric = isNumeric;