UNPKG

9.49 kBJavaScriptView Raw
1"use strict";
2
3function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
4
5Object.defineProperty(exports, "__esModule", {
6 value: true
7});
8exports.create = create;
9
10require("./../utils/polyfills.js");
11
12var _object = require("../utils/object.js");
13
14var emitter = _interopRequireWildcard(require("./../utils/emitter.js"));
15
16var _import = require("./function/import.js");
17
18var _config = require("./function/config.js");
19
20var _factory = require("../utils/factory.js");
21
22var _is = require("../utils/is.js");
23
24var _ArgumentsError = require("../error/ArgumentsError.js");
25
26var _DimensionError = require("../error/DimensionError.js");
27
28var _IndexError = require("../error/IndexError.js");
29
30var _config2 = require("./config.js");
31
32function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
33
34function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
35
36function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
37
38/**
39 * Create a mathjs instance from given factory functions and optionally config
40 *
41 * Usage:
42 *
43 * const mathjs1 = create({ createAdd, createMultiply, ...})
44 * const config = { number: 'BigNumber' }
45 * const mathjs2 = create(all, config)
46 *
47 * @param {Object} [factories] An object with factory functions
48 * The object can contain nested objects,
49 * all nested objects will be flattened.
50 * @param {Object} [config] Available options:
51 * {number} epsilon
52 * Minimum relative difference between two
53 * compared values, used by all comparison functions.
54 * {string} matrix
55 * A string 'Matrix' (default) or 'Array'.
56 * {string} number
57 * A string 'number' (default), 'BigNumber', or 'Fraction'
58 * {number} precision
59 * The number of significant digits for BigNumbers.
60 * Not applicable for Numbers.
61 * {boolean} predictable
62 * Predictable output type of functions. When true,
63 * output type depends only on the input types. When
64 * false (default), output type can vary depending
65 * on input values. For example `math.sqrt(-4)`
66 * returns `complex('2i')` when predictable is false, and
67 * returns `NaN` when true.
68 * {string} randomSeed
69 * Random seed for seeded pseudo random number generator.
70 * Set to null to randomly seed.
71 * @returns {Object} Returns a bare-bone math.js instance containing
72 * functions:
73 * - `import` to add new functions
74 * - `config` to change configuration
75 * - `on`, `off`, `once`, `emit` for events
76 */
77function create(factories, config) {
78 var configInternal = _extends({}, _config2.DEFAULT_CONFIG, config); // simple test for ES5 support
79
80
81 if (typeof Object.create !== 'function') {
82 throw new Error('ES5 not supported by this JavaScript engine. ' + 'Please load the es5-shim and es5-sham library for compatibility.');
83 } // create the mathjs instance
84
85
86 var math = emitter.mixin({
87 // only here for backward compatibility for legacy factory functions
88 isNumber: _is.isNumber,
89 isComplex: _is.isComplex,
90 isBigNumber: _is.isBigNumber,
91 isFraction: _is.isFraction,
92 isUnit: _is.isUnit,
93 isString: _is.isString,
94 isArray: _is.isArray,
95 isMatrix: _is.isMatrix,
96 isCollection: _is.isCollection,
97 isDenseMatrix: _is.isDenseMatrix,
98 isSparseMatrix: _is.isSparseMatrix,
99 isRange: _is.isRange,
100 isIndex: _is.isIndex,
101 isBoolean: _is.isBoolean,
102 isResultSet: _is.isResultSet,
103 isHelp: _is.isHelp,
104 isFunction: _is.isFunction,
105 isDate: _is.isDate,
106 isRegExp: _is.isRegExp,
107 isObject: _is.isObject,
108 isNull: _is.isNull,
109 isUndefined: _is.isUndefined,
110 isAccessorNode: _is.isAccessorNode,
111 isArrayNode: _is.isArrayNode,
112 isAssignmentNode: _is.isAssignmentNode,
113 isBlockNode: _is.isBlockNode,
114 isConditionalNode: _is.isConditionalNode,
115 isConstantNode: _is.isConstantNode,
116 isFunctionAssignmentNode: _is.isFunctionAssignmentNode,
117 isFunctionNode: _is.isFunctionNode,
118 isIndexNode: _is.isIndexNode,
119 isNode: _is.isNode,
120 isObjectNode: _is.isObjectNode,
121 isOperatorNode: _is.isOperatorNode,
122 isParenthesisNode: _is.isParenthesisNode,
123 isRangeNode: _is.isRangeNode,
124 isSymbolNode: _is.isSymbolNode,
125 isChain: _is.isChain
126 }); // load config function and apply provided config
127
128 math.config = (0, _config.configFactory)(configInternal, math.emit);
129 math.expression = {
130 transform: {},
131 mathWithTransform: {
132 config: math.config
133 }
134 }; // cached factories and instances used by function load
135
136 var legacyFactories = [];
137 var legacyInstances = [];
138 /**
139 * Load a function or data type from a factory.
140 * If the function or data type already exists, the existing instance is
141 * returned.
142 * @param {Function} factory
143 * @returns {*}
144 */
145
146 function load(factory) {
147 if ((0, _factory.isFactory)(factory)) {
148 return factory(math);
149 }
150
151 var firstProperty = factory[Object.keys(factory)[0]];
152
153 if ((0, _factory.isFactory)(firstProperty)) {
154 return firstProperty(math);
155 }
156
157 if (!(0, _object.isLegacyFactory)(factory)) {
158 console.warn('Factory object with properties `type`, `name`, and `factory` expected', factory);
159 throw new Error('Factory object with properties `type`, `name`, and `factory` expected');
160 }
161
162 var index = legacyFactories.indexOf(factory);
163 var instance;
164
165 if (index === -1) {
166 // doesn't yet exist
167 if (factory.math === true) {
168 // pass with math namespace
169 instance = factory.factory(math.type, configInternal, load, math.typed, math);
170 } else {
171 instance = factory.factory(math.type, configInternal, load, math.typed);
172 } // append to the cache
173
174
175 legacyFactories.push(factory);
176 legacyInstances.push(instance);
177 } else {
178 // already existing function, return the cached instance
179 instance = legacyInstances[index];
180 }
181
182 return instance;
183 }
184
185 var importedFactories = {}; // load the import function
186
187 function lazyTyped() {
188 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
189 args[_key] = arguments[_key];
190 }
191
192 return math.typed.apply(math.typed, args);
193 }
194
195 var internalImport = (0, _import.importFactory)(lazyTyped, load, math, importedFactories);
196 math["import"] = internalImport; // listen for changes in config, import all functions again when changed
197 // TODO: move this listener into the import function?
198
199 math.on('config', function () {
200 (0, _object.values)(importedFactories).forEach(function (factory) {
201 if (factory && factory.meta && factory.meta.recreateOnConfigChange) {
202 // FIXME: only re-create when the current instance is the same as was initially created
203 // FIXME: delete the functions/constants before importing them again?
204 internalImport(factory, {
205 override: true
206 });
207 }
208 });
209 }); // the create function exposed on the mathjs instance is bound to
210 // the factory functions passed before
211
212 math.create = create.bind(null, factories); // export factory function
213
214 math.factory = _factory.factory; // import the factory functions like createAdd as an array instead of object,
215 // else they will get a different naming (`createAdd` instead of `add`).
216
217 math["import"]((0, _object.values)((0, _object.deepFlatten)(factories)));
218 math.ArgumentsError = _ArgumentsError.ArgumentsError;
219 math.DimensionError = _DimensionError.DimensionError;
220 math.IndexError = _IndexError.IndexError;
221 return math;
222}
\No newline at end of file