numeric.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { typeOf } from '../../utils/is.js';
  2. import { factory } from '../../utils/factory.js';
  3. import { noBignumber, noFraction } from '../../utils/noop.js';
  4. var name = 'numeric';
  5. var dependencies = ['number', '?bignumber', '?fraction'];
  6. export var createNumeric = /* #__PURE__ */factory(name, dependencies, _ref => {
  7. var {
  8. number: _number,
  9. bignumber,
  10. fraction
  11. } = _ref;
  12. var validInputTypes = {
  13. string: true,
  14. number: true,
  15. BigNumber: true,
  16. Fraction: true
  17. };
  18. // Load the conversion functions for each output type
  19. var validOutputTypes = {
  20. number: x => _number(x),
  21. BigNumber: bignumber ? x => bignumber(x) : noBignumber,
  22. Fraction: fraction ? x => fraction(x) : noFraction
  23. };
  24. /**
  25. * Convert a numeric input to a specific numeric type: number, BigNumber, or Fraction.
  26. *
  27. * Syntax:
  28. *
  29. * math.numeric(x)
  30. *
  31. * Examples:
  32. *
  33. * math.numeric('4') // returns 4
  34. * math.numeric('4', 'number') // returns 4
  35. * math.numeric('4', 'BigNumber') // returns BigNumber 4
  36. * math.numeric('4', 'Fraction') // returns Fraction 4
  37. * math.numeric(4, 'Fraction') // returns Fraction 4
  38. * math.numeric(math.fraction(2, 5), 'number') // returns 0.4
  39. *
  40. * See also:
  41. *
  42. * number, fraction, bignumber, string, format
  43. *
  44. * @param {string | number | BigNumber | Fraction } value
  45. * A numeric value or a string containing a numeric value
  46. * @param {string} outputType
  47. * Desired numeric output type.
  48. * Available values: 'number', 'BigNumber', or 'Fraction'
  49. * @return {number | BigNumber | Fraction}
  50. * Returns an instance of the numeric in the requested type
  51. */
  52. return function numeric(value) {
  53. var outputType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'number';
  54. var check = arguments.length > 2 ? arguments[2] : undefined;
  55. if (check !== undefined) {
  56. throw new SyntaxError('numeric() takes one or two arguments');
  57. }
  58. var inputType = typeOf(value);
  59. if (!(inputType in validInputTypes)) {
  60. throw new TypeError('Cannot convert ' + value + ' of type "' + inputType + '"; valid input types are ' + Object.keys(validInputTypes).join(', '));
  61. }
  62. if (!(outputType in validOutputTypes)) {
  63. throw new TypeError('Cannot convert ' + value + ' to type "' + outputType + '"; valid output types are ' + Object.keys(validOutputTypes).join(', '));
  64. }
  65. if (outputType === inputType) {
  66. return value;
  67. } else {
  68. return validOutputTypes[outputType](value);
  69. }
  70. };
  71. });