UNPKG

1.98 kBJavaScriptView Raw
1'use strict'
2
3function factory (type, config, load, typed) {
4 const getTypeOf = load(require('../function/utils/typeof'))
5
6 const validInputTypes = {
7 'string': true,
8 'number': true,
9 'BigNumber': true,
10 'Fraction': true
11 }
12
13 // Load the conversion functions for each output type
14 const validOutputTypes = {
15 'number': load(require('./number')),
16 'BigNumber': load(require('./bignumber/function/bignumber')),
17 'Fraction': load(require('./fraction/function/fraction'))
18 }
19
20 /**
21 * Convert a numeric value to a specific type: number, BigNumber, or Fraction
22 *
23 * @param {string | number | BigNumber | Fraction } value
24 * @param {'number' | 'BigNumber' | 'Fraction'} outputType
25 * @return {number | BigNumber | Fraction} Returns an instance of the
26 * numeric in the requested type
27 */
28 const numeric = function (value, outputType) {
29 const inputType = getTypeOf(value)
30
31 if (!(inputType in validInputTypes)) {
32 throw new TypeError('Cannot convert ' + value + ' of type "' + inputType + '"; valid input types are ' + Object.keys(validInputTypes).join(', '))
33 }
34 if (!(outputType in validOutputTypes)) {
35 throw new TypeError('Cannot convert ' + value + ' to type "' + outputType + '"; valid output types are ' + Object.keys(validOutputTypes).join(', '))
36 }
37
38 if (outputType === inputType) {
39 return value
40 } else {
41 return validOutputTypes[outputType](value)
42 }
43 }
44
45 numeric.toTex = function (node, options) {
46 // Not sure if this is strictly right but should work correctly for the vast majority of use cases.
47 return node.args[0].toTex()
48 }
49
50 return numeric
51}
52
53// FIXME: expose numeric in the math namespace after we've decided on a name and have written proper docs for this function. See https://github.com/josdejong/mathjs/pull/1270
54// exports.name = 'type._numeric'
55exports.path = 'type'
56exports.name = '_numeric'
57exports.factory = factory