UNPKG

19.8 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.isInteger = isInteger;
7exports.format = format;
8exports.splitNumber = splitNumber;
9exports.toEngineering = toEngineering;
10exports.toFixed = toFixed;
11exports.toExponential = toExponential;
12exports.toPrecision = toPrecision;
13exports.roundDigits = roundDigits;
14exports.digits = digits;
15exports.nearlyEqual = nearlyEqual;
16exports.tanh = exports.sinh = exports.cosh = exports.atanh = exports.asinh = exports.acosh = exports.DBL_EPSILON = exports.expm1 = exports.cbrt = exports.log1p = exports.log10 = exports.log2 = exports.sign = void 0;
17
18var _object = require("./object");
19
20var _is = require("./is");
21
22function isInteger(value) {
23 if (typeof value === 'boolean') {
24 return true;
25 }
26
27 return isFinite(value) ? value === Math.round(value) : false; // Note: we use ==, not ===, as we can have Booleans as well
28}
29/**
30 * Calculate the sign of a number
31 * @param {number} x
32 * @returns {number}
33 */
34
35
36var sign =
37/* #__PURE__ */
38Math.sign || function (x) {
39 if (x > 0) {
40 return 1;
41 } else if (x < 0) {
42 return -1;
43 } else {
44 return 0;
45 }
46};
47/**
48 * Calculate the base-2 logarithm of a number
49 * @param {number} x
50 * @returns {number}
51 */
52
53
54exports.sign = sign;
55
56var log2 =
57/* #__PURE__ */
58Math.log2 || function log2(x) {
59 return Math.log(x) / Math.LN2;
60};
61/**
62 * Calculate the base-10 logarithm of a number
63 * @param {number} x
64 * @returns {number}
65 */
66
67
68exports.log2 = log2;
69
70var log10 =
71/* #__PURE__ */
72Math.log10 || function log10(x) {
73 return Math.log(x) / Math.LN10;
74};
75/**
76 * Calculate the natural logarithm of a number + 1
77 * @param {number} x
78 * @returns {number}
79 */
80
81
82exports.log10 = log10;
83
84var log1p =
85/* #__PURE__ */
86Math.log1p || function (x) {
87 return Math.log(x + 1);
88};
89/**
90 * Calculate cubic root for a number
91 *
92 * Code from es6-shim.js:
93 * https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1564-L1577
94 *
95 * @param {number} x
96 * @returns {number} Returns the cubic root of x
97 */
98
99
100exports.log1p = log1p;
101
102var cbrt =
103/* #__PURE__ */
104Math.cbrt || function cbrt(x) {
105 if (x === 0) {
106 return x;
107 }
108
109 var negate = x < 0;
110 var result;
111
112 if (negate) {
113 x = -x;
114 }
115
116 if (isFinite(x)) {
117 result = Math.exp(Math.log(x) / 3); // from https://en.wikipedia.org/wiki/Cube_root#Numerical_methods
118
119 result = (x / (result * result) + 2 * result) / 3;
120 } else {
121 result = x;
122 }
123
124 return negate ? -result : result;
125};
126/**
127 * Calculates exponentiation minus 1
128 * @param {number} x
129 * @return {number} res
130 */
131
132
133exports.cbrt = cbrt;
134
135var expm1 =
136/* #__PURE__ */
137Math.expm1 || function expm1(x) {
138 return x >= 2e-4 || x <= -2e-4 ? Math.exp(x) - 1 : x + x * x / 2 + x * x * x / 6;
139};
140/**
141 * Convert a number to a formatted string representation.
142 *
143 * Syntax:
144 *
145 * format(value)
146 * format(value, options)
147 * format(value, precision)
148 * format(value, fn)
149 *
150 * Where:
151 *
152 * {number} value The value to be formatted
153 * {Object} options An object with formatting options. Available options:
154 * {string} notation
155 * Number notation. Choose from:
156 * 'fixed' Always use regular number notation.
157 * For example '123.40' and '14000000'
158 * 'exponential' Always use exponential notation.
159 * For example '1.234e+2' and '1.4e+7'
160 * 'engineering' Always use engineering notation.
161 * For example '123.4e+0' and '14.0e+6'
162 * 'auto' (default) Regular number notation for numbers
163 * having an absolute value between
164 * `lowerExp` and `upperExp` bounds, and
165 * uses exponential notation elsewhere.
166 * Lower bound is included, upper bound
167 * is excluded.
168 * For example '123.4' and '1.4e7'.
169 * {number} precision A number between 0 and 16 to round
170 * the digits of the number.
171 * In case of notations 'exponential',
172 * 'engineering', and 'auto',
173 * `precision` defines the total
174 * number of significant digits returned.
175 * In case of notation 'fixed',
176 * `precision` defines the number of
177 * significant digits after the decimal
178 * point.
179 * `precision` is undefined by default,
180 * not rounding any digits.
181 * {number} lowerExp Exponent determining the lower boundary
182 * for formatting a value with an exponent
183 * when `notation='auto`.
184 * Default value is `-3`.
185 * {number} upperExp Exponent determining the upper boundary
186 * for formatting a value with an exponent
187 * when `notation='auto`.
188 * Default value is `5`.
189 * {Function} fn A custom formatting function. Can be used to override the
190 * built-in notations. Function `fn` is called with `value` as
191 * parameter and must return a string. Is useful for example to
192 * format all values inside a matrix in a particular way.
193 *
194 * Examples:
195 *
196 * format(6.4) // '6.4'
197 * format(1240000) // '1.24e6'
198 * format(1/3) // '0.3333333333333333'
199 * format(1/3, 3) // '0.333'
200 * format(21385, 2) // '21000'
201 * format(12.071, {notation: 'fixed'}) // '12'
202 * format(2.3, {notation: 'fixed', precision: 2}) // '2.30'
203 * format(52.8, {notation: 'exponential'}) // '5.28e+1'
204 * format(12345678, {notation: 'engineering'}) // '12.345678e+6'
205 *
206 * @param {number} value
207 * @param {Object | Function | number} [options]
208 * @return {string} str The formatted value
209 */
210
211
212exports.expm1 = expm1;
213
214function format(value, options) {
215 if (typeof options === 'function') {
216 // handle format(value, fn)
217 return options(value);
218 } // handle special cases
219
220
221 if (value === Infinity) {
222 return 'Infinity';
223 } else if (value === -Infinity) {
224 return '-Infinity';
225 } else if (isNaN(value)) {
226 return 'NaN';
227 } // default values for options
228
229
230 var notation = 'auto';
231 var precision;
232
233 if (options) {
234 // determine notation from options
235 if (options.notation) {
236 notation = options.notation;
237 } // determine precision from options
238
239
240 if ((0, _is.isNumber)(options)) {
241 precision = options;
242 } else if ((0, _is.isNumber)(options.precision)) {
243 precision = options.precision;
244 }
245 } // handle the various notations
246
247
248 switch (notation) {
249 case 'fixed':
250 return toFixed(value, precision);
251
252 case 'exponential':
253 return toExponential(value, precision);
254
255 case 'engineering':
256 return toEngineering(value, precision);
257
258 case 'auto':
259 // TODO: clean up some day. Deprecated since: 2018-01-24
260 // @deprecated upper and lower are replaced with upperExp and lowerExp since v4.0.0
261 if (options && options.exponential && (options.exponential.lower !== undefined || options.exponential.upper !== undefined)) {
262 var fixedOptions = (0, _object.mapObject)(options, function (x) {
263 return x;
264 });
265 fixedOptions.exponential = undefined;
266
267 if (options.exponential.lower !== undefined) {
268 fixedOptions.lowerExp = Math.round(Math.log(options.exponential.lower) / Math.LN10);
269 }
270
271 if (options.exponential.upper !== undefined) {
272 fixedOptions.upperExp = Math.round(Math.log(options.exponential.upper) / Math.LN10);
273 }
274
275 console.warn('Deprecation warning: Formatting options exponential.lower and exponential.upper ' + '(minimum and maximum value) ' + 'are replaced with exponential.lowerExp and exponential.upperExp ' + '(minimum and maximum exponent) since version 4.0.0. ' + 'Replace ' + JSON.stringify(options) + ' with ' + JSON.stringify(fixedOptions));
276 return toPrecision(value, precision, fixedOptions);
277 } // remove trailing zeros after the decimal point
278
279
280 return toPrecision(value, precision, options && options).replace(/((\.\d*?)(0+))($|e)/, function () {
281 var digits = arguments[2];
282 var e = arguments[4];
283 return digits !== '.' ? digits + e : e;
284 });
285
286 default:
287 throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", or "fixed".');
288 }
289}
290/**
291 * Split a number into sign, coefficients, and exponent
292 * @param {number | string} value
293 * @return {SplitValue}
294 * Returns an object containing sign, coefficients, and exponent
295 */
296
297
298function splitNumber(value) {
299 // parse the input value
300 var match = String(value).toLowerCase().match(/^0*?(-?)(\d+\.?\d*)(e([+-]?\d+))?$/);
301
302 if (!match) {
303 throw new SyntaxError('Invalid number ' + value);
304 }
305
306 var sign = match[1];
307 var digits = match[2];
308 var exponent = parseFloat(match[4] || '0');
309 var dot = digits.indexOf('.');
310 exponent += dot !== -1 ? dot - 1 : digits.length - 1;
311 var coefficients = digits.replace('.', '') // remove the dot (must be removed before removing leading zeros)
312 .replace(/^0*/, function (zeros) {
313 // remove leading zeros, add their count to the exponent
314 exponent -= zeros.length;
315 return '';
316 }).replace(/0*$/, '') // remove trailing zeros
317 .split('').map(function (d) {
318 return parseInt(d);
319 });
320
321 if (coefficients.length === 0) {
322 coefficients.push(0);
323 exponent++;
324 }
325
326 return {
327 sign: sign,
328 coefficients: coefficients,
329 exponent: exponent
330 };
331}
332/**
333 * Format a number in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3'
334 * @param {number | string} value
335 * @param {number} [precision] Optional number of significant figures to return.
336 */
337
338
339function toEngineering(value, precision) {
340 if (isNaN(value) || !isFinite(value)) {
341 return String(value);
342 }
343
344 var rounded = roundDigits(splitNumber(value), precision);
345 var e = rounded.exponent;
346 var c = rounded.coefficients; // find nearest lower multiple of 3 for exponent
347
348 var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3;
349
350 if ((0, _is.isNumber)(precision)) {
351 // add zeroes to give correct sig figs
352 while (precision > c.length || e - newExp + 1 > c.length) {
353 c.push(0);
354 }
355 } else {
356 // concatenate coefficients with necessary zeros
357 var significandsDiff = e >= 0 ? e : Math.abs(newExp); // add zeros if necessary (for ex: 1e+8)
358
359 while (c.length - 1 < significandsDiff) {
360 c.push(0);
361 }
362 } // find difference in exponents
363
364
365 var expDiff = Math.abs(e - newExp);
366 var decimalIdx = 1; // push decimal index over by expDiff times
367
368 while (expDiff > 0) {
369 decimalIdx++;
370 expDiff--;
371 } // if all coefficient values are zero after the decimal point and precision is unset, don't add a decimal value.
372 // otherwise concat with the rest of the coefficients
373
374
375 var decimals = c.slice(decimalIdx).join('');
376 var decimalVal = (0, _is.isNumber)(precision) && decimals.length || decimals.match(/[1-9]/) ? '.' + decimals : '';
377 var str = c.slice(0, decimalIdx).join('') + decimalVal + 'e' + (e >= 0 ? '+' : '') + newExp.toString();
378 return rounded.sign + str;
379}
380/**
381 * Format a number with fixed notation.
382 * @param {number | string} value
383 * @param {number} [precision=undefined] Optional number of decimals after the
384 * decimal point. null by default.
385 */
386
387
388function toFixed(value, precision) {
389 if (isNaN(value) || !isFinite(value)) {
390 return String(value);
391 }
392
393 var splitValue = splitNumber(value);
394 var rounded = typeof precision === 'number' ? roundDigits(splitValue, splitValue.exponent + 1 + precision) : splitValue;
395 var c = rounded.coefficients;
396 var p = rounded.exponent + 1; // exponent may have changed
397 // append zeros if needed
398
399 var pp = p + (precision || 0);
400
401 if (c.length < pp) {
402 c = c.concat(zeros(pp - c.length));
403 } // prepend zeros if needed
404
405
406 if (p < 0) {
407 c = zeros(-p + 1).concat(c);
408 p = 1;
409 } // insert a dot if needed
410
411
412 if (p < c.length) {
413 c.splice(p, 0, p === 0 ? '0.' : '.');
414 }
415
416 return rounded.sign + c.join('');
417}
418/**
419 * Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3'
420 * @param {number | string} value
421 * @param {number} [precision] Number of digits in formatted output.
422 * If not provided, the maximum available digits
423 * is used.
424 */
425
426
427function toExponential(value, precision) {
428 if (isNaN(value) || !isFinite(value)) {
429 return String(value);
430 } // round if needed, else create a clone
431
432
433 var split = splitNumber(value);
434 var rounded = precision ? roundDigits(split, precision) : split;
435 var c = rounded.coefficients;
436 var e = rounded.exponent; // append zeros if needed
437
438 if (c.length < precision) {
439 c = c.concat(zeros(precision - c.length));
440 } // format as `C.CCCe+EEE` or `C.CCCe-EEE`
441
442
443 var first = c.shift();
444 return rounded.sign + first + (c.length > 0 ? '.' + c.join('') : '') + 'e' + (e >= 0 ? '+' : '') + e;
445}
446/**
447 * Format a number with a certain precision
448 * @param {number | string} value
449 * @param {number} [precision=undefined] Optional number of digits.
450 * @param {{lowerExp: number | undefined, upperExp: number | undefined}} [options]
451 * By default:
452 * lowerExp = -3 (incl)
453 * upper = +5 (excl)
454 * @return {string}
455 */
456
457
458function toPrecision(value, precision, options) {
459 if (isNaN(value) || !isFinite(value)) {
460 return String(value);
461 } // determine lower and upper bound for exponential notation.
462
463
464 var lowerExp = options && options.lowerExp !== undefined ? options.lowerExp : -3;
465 var upperExp = options && options.upperExp !== undefined ? options.upperExp : 5;
466 var split = splitNumber(value);
467 var rounded = precision ? roundDigits(split, precision) : split;
468
469 if (rounded.exponent < lowerExp || rounded.exponent >= upperExp) {
470 // exponential notation
471 return toExponential(value, precision);
472 } else {
473 var c = rounded.coefficients;
474 var e = rounded.exponent; // append trailing zeros
475
476 if (c.length < precision) {
477 c = c.concat(zeros(precision - c.length));
478 } // append trailing zeros
479 // TODO: simplify the next statement
480
481
482 c = c.concat(zeros(e - c.length + 1 + (c.length < precision ? precision - c.length : 0))); // prepend zeros
483
484 c = zeros(-e).concat(c);
485 var dot = e > 0 ? e : 0;
486
487 if (dot < c.length - 1) {
488 c.splice(dot + 1, 0, '.');
489 }
490
491 return rounded.sign + c.join('');
492 }
493}
494/**
495 * Round the number of digits of a number *
496 * @param {SplitValue} split A value split with .splitNumber(value)
497 * @param {number} precision A positive integer
498 * @return {SplitValue}
499 * Returns an object containing sign, coefficients, and exponent
500 * with rounded digits
501 */
502
503
504function roundDigits(split, precision) {
505 // create a clone
506 var rounded = {
507 sign: split.sign,
508 coefficients: split.coefficients,
509 exponent: split.exponent
510 };
511 var c = rounded.coefficients; // prepend zeros if needed
512
513 while (precision <= 0) {
514 c.unshift(0);
515 rounded.exponent++;
516 precision++;
517 }
518
519 if (c.length > precision) {
520 var removed = c.splice(precision, c.length - precision);
521
522 if (removed[0] >= 5) {
523 var i = precision - 1;
524 c[i]++;
525
526 while (c[i] === 10) {
527 c.pop();
528
529 if (i === 0) {
530 c.unshift(0);
531 rounded.exponent++;
532 i++;
533 }
534
535 i--;
536 c[i]++;
537 }
538 }
539 }
540
541 return rounded;
542}
543/**
544 * Create an array filled with zeros.
545 * @param {number} length
546 * @return {Array}
547 */
548
549
550function zeros(length) {
551 var arr = [];
552
553 for (var i = 0; i < length; i++) {
554 arr.push(0);
555 }
556
557 return arr;
558}
559/**
560 * Count the number of significant digits of a number.
561 *
562 * For example:
563 * 2.34 returns 3
564 * 0.0034 returns 2
565 * 120.5e+30 returns 4
566 *
567 * @param {number} value
568 * @return {number} digits Number of significant digits
569 */
570
571
572function digits(value) {
573 return value.toExponential().replace(/e.*$/, '') // remove exponential notation
574 .replace(/^0\.?0*|\./, '') // remove decimal point and leading zeros
575 .length;
576}
577/**
578 * Minimum number added to one that makes the result different than one
579 */
580
581
582var DBL_EPSILON = Number.EPSILON || 2.2204460492503130808472633361816E-16;
583/**
584 * Compares two floating point numbers.
585 * @param {number} x First value to compare
586 * @param {number} y Second value to compare
587 * @param {number} [epsilon] The maximum relative difference between x and y
588 * If epsilon is undefined or null, the function will
589 * test whether x and y are exactly equal.
590 * @return {boolean} whether the two numbers are nearly equal
591*/
592
593exports.DBL_EPSILON = DBL_EPSILON;
594
595function nearlyEqual(x, y, epsilon) {
596 // if epsilon is null or undefined, test whether x and y are exactly equal
597 if (epsilon === null || epsilon === undefined) {
598 return x === y;
599 }
600
601 if (x === y) {
602 return true;
603 } // NaN
604
605
606 if (isNaN(x) || isNaN(y)) {
607 return false;
608 } // at this point x and y should be finite
609
610
611 if (isFinite(x) && isFinite(y)) {
612 // check numbers are very close, needed when comparing numbers near zero
613 var diff = Math.abs(x - y);
614
615 if (diff < DBL_EPSILON) {
616 return true;
617 } else {
618 // use relative error
619 return diff <= Math.max(Math.abs(x), Math.abs(y)) * epsilon;
620 }
621 } // Infinite and Number or negative Infinite and positive Infinite cases
622
623
624 return false;
625}
626/**
627 * Calculate the hyperbolic arccos of a number
628 * @param {number} x
629 * @return {number}
630 */
631
632
633var acosh = Math.acosh || function (x) {
634 return Math.log(Math.sqrt(x * x - 1) + x);
635};
636
637exports.acosh = acosh;
638
639var asinh = Math.asinh || function (x) {
640 return Math.log(Math.sqrt(x * x + 1) + x);
641};
642/**
643 * Calculate the hyperbolic arctangent of a number
644 * @param {number} x
645 * @return {number}
646 */
647
648
649exports.asinh = asinh;
650
651var atanh = Math.atanh || function (x) {
652 return Math.log((1 + x) / (1 - x)) / 2;
653};
654/**
655 * Calculate the hyperbolic cosine of a number
656 * @param {number} x
657 * @returns {number}
658 */
659
660
661exports.atanh = atanh;
662
663var cosh = Math.cosh || function (x) {
664 return (Math.exp(x) + Math.exp(-x)) / 2;
665};
666/**
667 * Calculate the hyperbolic sine of a number
668 * @param {number} x
669 * @returns {number}
670 */
671
672
673exports.cosh = cosh;
674
675var sinh = Math.sinh || function (x) {
676 return (Math.exp(x) - Math.exp(-x)) / 2;
677};
678/**
679 * Calculate the hyperbolic tangent of a number
680 * @param {number} x
681 * @returns {number}
682 */
683
684
685exports.sinh = sinh;
686
687var tanh = Math.tanh || function (x) {
688 var e = Math.exp(2 * x);
689 return (e - 1) / (e + 1);
690};
691
692exports.tanh = tanh;
\No newline at end of file