number.js 16 KB

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