UNPKG

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