feat:node-modules

This commit is contained in:
houjunxiang
2025-11-24 10:26:18 +08:00
parent 753766893b
commit 8a3e48d856
8825 changed files with 567399 additions and 1 deletions

837
node_modules/mathjs/lib/esm/utils/array.js generated vendored Normal file
View File

@@ -0,0 +1,837 @@
import _extends from "@babel/runtime/helpers/extends";
import { isInteger } from './number.js';
import { isNumber, isBigNumber, isArray, isString } from './is.js';
import { format } from './string.js';
import { DimensionError } from '../error/DimensionError.js';
import { IndexError } from '../error/IndexError.js';
import { deepStrictEqual } from './object.js';
/**
* Calculate the size of a multi dimensional array.
* This function checks the size of the first entry, it does not validate
* whether all dimensions match. (use function `validate` for that)
* @param {Array} x
* @Return {Number[]} size
*/
export function arraySize(x) {
var s = [];
while (Array.isArray(x)) {
s.push(x.length);
x = x[0];
}
return s;
}
/**
* Recursively validate whether each element in a multi dimensional array
* has a size corresponding to the provided size array.
* @param {Array} array Array to be validated
* @param {number[]} size Array with the size of each dimension
* @param {number} dim Current dimension
* @throws DimensionError
* @private
*/
function _validate(array, size, dim) {
var i;
var len = array.length;
if (len !== size[dim]) {
throw new DimensionError(len, size[dim]);
}
if (dim < size.length - 1) {
// recursively validate each child array
var dimNext = dim + 1;
for (i = 0; i < len; i++) {
var child = array[i];
if (!Array.isArray(child)) {
throw new DimensionError(size.length - 1, size.length, '<');
}
_validate(array[i], size, dimNext);
}
} else {
// last dimension. none of the childs may be an array
for (i = 0; i < len; i++) {
if (Array.isArray(array[i])) {
throw new DimensionError(size.length + 1, size.length, '>');
}
}
}
}
/**
* Validate whether each element in a multi dimensional array has
* a size corresponding to the provided size array.
* @param {Array} array Array to be validated
* @param {number[]} size Array with the size of each dimension
* @throws DimensionError
*/
export function validate(array, size) {
var isScalar = size.length === 0;
if (isScalar) {
// scalar
if (Array.isArray(array)) {
throw new DimensionError(array.length, 0);
}
} else {
// array
_validate(array, size, 0);
}
}
/**
* Validate whether the source of the index matches the size of the Array
* @param {Array | Matrix} array Array to be validated
* @param {Index} index Index with the source information to validate
* @throws DimensionError
*/
export function validateIndexSourceSize(value, index) {
var valueSize = value.isMatrix ? value._size : arraySize(value);
var sourceSize = index._sourceSize;
// checks if the source size is not null and matches the valueSize
sourceSize.forEach((sourceDim, i) => {
if (sourceDim !== null && sourceDim !== valueSize[i]) {
throw new DimensionError(sourceDim, valueSize[i]);
}
});
}
/**
* Test whether index is an integer number with index >= 0 and index < length
* when length is provided
* @param {number} index Zero-based index
* @param {number} [length] Length of the array
*/
export function validateIndex(index, length) {
if (index !== undefined) {
if (!isNumber(index) || !isInteger(index)) {
throw new TypeError('Index must be an integer (value: ' + index + ')');
}
if (index < 0 || typeof length === 'number' && index >= length) {
throw new IndexError(index, length);
}
}
}
/**
* Test if and index has empty values
* @param {number} index Zero-based index
*/
export function isEmptyIndex(index) {
for (var i = 0; i < index._dimensions.length; ++i) {
var dimension = index._dimensions[i];
if (dimension._data && isArray(dimension._data)) {
if (dimension._size[0] === 0) {
return true;
}
} else if (dimension.isRange) {
if (dimension.start === dimension.end) {
return true;
}
} else if (isString(dimension)) {
if (dimension.length === 0) {
return true;
}
}
}
return false;
}
/**
* Resize a multi dimensional array. The resized array is returned.
* @param {Array | number} array Array to be resized
* @param {number[]} size Array with the size of each dimension
* @param {*} [defaultValue=0] Value to be filled in in new entries,
* zero by default. Specify for example `null`,
* to clearly see entries that are not explicitly
* set.
* @return {Array} array The resized array
*/
export function resize(array, size, defaultValue) {
// check the type of the arguments
if (!Array.isArray(size)) {
throw new TypeError('Array expected');
}
if (size.length === 0) {
throw new Error('Resizing to scalar is not supported');
}
// check whether size contains positive integers
size.forEach(function (value) {
if (!isNumber(value) || !isInteger(value) || value < 0) {
throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + format(size) + ')');
}
});
// convert number to an array
if (isNumber(array) || isBigNumber(array)) {
array = [array];
}
// recursively resize the array
var _defaultValue = defaultValue !== undefined ? defaultValue : 0;
_resize(array, size, 0, _defaultValue);
return array;
}
/**
* Recursively resize a multi dimensional array
* @param {Array} array Array to be resized
* @param {number[]} size Array with the size of each dimension
* @param {number} dim Current dimension
* @param {*} [defaultValue] Value to be filled in in new entries,
* undefined by default.
* @private
*/
function _resize(array, size, dim, defaultValue) {
var i;
var elem;
var oldLen = array.length;
var newLen = size[dim];
var minLen = Math.min(oldLen, newLen);
// apply new length
array.length = newLen;
if (dim < size.length - 1) {
// non-last dimension
var dimNext = dim + 1;
// resize existing child arrays
for (i = 0; i < minLen; i++) {
// resize child array
elem = array[i];
if (!Array.isArray(elem)) {
elem = [elem]; // add a dimension
array[i] = elem;
}
_resize(elem, size, dimNext, defaultValue);
}
// create new child arrays
for (i = minLen; i < newLen; i++) {
// get child array
elem = [];
array[i] = elem;
// resize new child array
_resize(elem, size, dimNext, defaultValue);
}
} else {
// last dimension
// remove dimensions of existing values
for (i = 0; i < minLen; i++) {
while (Array.isArray(array[i])) {
array[i] = array[i][0];
}
}
// fill new elements with the default value
for (i = minLen; i < newLen; i++) {
array[i] = defaultValue;
}
}
}
/**
* Re-shape a multi dimensional array to fit the specified dimensions
* @param {Array} array Array to be reshaped
* @param {number[]} sizes List of sizes for each dimension
* @returns {Array} Array whose data has been formatted to fit the
* specified dimensions
*
* @throws {DimensionError} If the product of the new dimension sizes does
* not equal that of the old ones
*/
export function reshape(array, sizes) {
var flatArray = flatten(array);
var currentLength = flatArray.length;
if (!Array.isArray(array) || !Array.isArray(sizes)) {
throw new TypeError('Array expected');
}
if (sizes.length === 0) {
throw new DimensionError(0, currentLength, '!=');
}
sizes = processSizesWildcard(sizes, currentLength);
var newLength = product(sizes);
if (currentLength !== newLength) {
throw new DimensionError(newLength, currentLength, '!=');
}
try {
return _reshape(flatArray, sizes);
} catch (e) {
if (e instanceof DimensionError) {
throw new DimensionError(newLength, currentLength, '!=');
}
throw e;
}
}
/**
* Replaces the wildcard -1 in the sizes array.
* @param {number[]} sizes List of sizes for each dimension. At most on wildcard.
* @param {number} currentLength Number of elements in the array.
* @throws {Error} If more than one wildcard or unable to replace it.
* @returns {number[]} The sizes array with wildcard replaced.
*/
export function processSizesWildcard(sizes, currentLength) {
var newLength = product(sizes);
var processedSizes = sizes.slice();
var WILDCARD = -1;
var wildCardIndex = sizes.indexOf(WILDCARD);
var isMoreThanOneWildcard = sizes.indexOf(WILDCARD, wildCardIndex + 1) >= 0;
if (isMoreThanOneWildcard) {
throw new Error('More than one wildcard in sizes');
}
var hasWildcard = wildCardIndex >= 0;
var canReplaceWildcard = currentLength % newLength === 0;
if (hasWildcard) {
if (canReplaceWildcard) {
processedSizes[wildCardIndex] = -currentLength / newLength;
} else {
throw new Error('Could not replace wildcard, since ' + currentLength + ' is no multiple of ' + -newLength);
}
}
return processedSizes;
}
/**
* Computes the product of all array elements.
* @param {number[]} array Array of factors
* @returns {number} Product of all elements
*/
function product(array) {
return array.reduce((prev, curr) => prev * curr, 1);
}
/**
* Iteratively re-shape a multi dimensional array to fit the specified dimensions
* @param {Array} array Array to be reshaped
* @param {number[]} sizes List of sizes for each dimension
* @returns {Array} Array whose data has been formatted to fit the
* specified dimensions
*/
function _reshape(array, sizes) {
// testing if there are enough elements for the requested shape
var tmpArray = array;
var tmpArray2;
// for each dimensions starting by the last one and ignoring the first one
for (var sizeIndex = sizes.length - 1; sizeIndex > 0; sizeIndex--) {
var size = sizes[sizeIndex];
tmpArray2 = [];
// aggregate the elements of the current tmpArray in elements of the requested size
var length = tmpArray.length / size;
for (var i = 0; i < length; i++) {
tmpArray2.push(tmpArray.slice(i * size, (i + 1) * size));
}
// set it as the new tmpArray for the next loop turn or for return
tmpArray = tmpArray2;
}
return tmpArray;
}
/**
* Squeeze a multi dimensional array
* @param {Array} array
* @param {Array} [size]
* @returns {Array} returns the array itself
*/
export function squeeze(array, size) {
var s = size || arraySize(array);
// squeeze outer dimensions
while (Array.isArray(array) && array.length === 1) {
array = array[0];
s.shift();
}
// find the first dimension to be squeezed
var dims = s.length;
while (s[dims - 1] === 1) {
dims--;
}
// squeeze inner dimensions
if (dims < s.length) {
array = _squeeze(array, dims, 0);
s.length = dims;
}
return array;
}
/**
* Recursively squeeze a multi dimensional array
* @param {Array} array
* @param {number} dims Required number of dimensions
* @param {number} dim Current dimension
* @returns {Array | *} Returns the squeezed array
* @private
*/
function _squeeze(array, dims, dim) {
var i, ii;
if (dim < dims) {
var next = dim + 1;
for (i = 0, ii = array.length; i < ii; i++) {
array[i] = _squeeze(array[i], dims, next);
}
} else {
while (Array.isArray(array)) {
array = array[0];
}
}
return array;
}
/**
* Unsqueeze a multi dimensional array: add dimensions when missing
*
* Paramter `size` will be mutated to match the new, unqueezed matrix size.
*
* @param {Array} array
* @param {number} dims Desired number of dimensions of the array
* @param {number} [outer] Number of outer dimensions to be added
* @param {Array} [size] Current size of array.
* @returns {Array} returns the array itself
* @private
*/
export function unsqueeze(array, dims, outer, size) {
var s = size || arraySize(array);
// unsqueeze outer dimensions
if (outer) {
for (var i = 0; i < outer; i++) {
array = [array];
s.unshift(1);
}
}
// unsqueeze inner dimensions
array = _unsqueeze(array, dims, 0);
while (s.length < dims) {
s.push(1);
}
return array;
}
/**
* Recursively unsqueeze a multi dimensional array
* @param {Array} array
* @param {number} dims Required number of dimensions
* @param {number} dim Current dimension
* @returns {Array | *} Returns the squeezed array
* @private
*/
function _unsqueeze(array, dims, dim) {
var i, ii;
if (Array.isArray(array)) {
var next = dim + 1;
for (i = 0, ii = array.length; i < ii; i++) {
array[i] = _unsqueeze(array[i], dims, next);
}
} else {
for (var d = dim; d < dims; d++) {
array = [array];
}
}
return array;
}
/**
* Flatten a multi dimensional array, put all elements in a one dimensional
* array
* @param {Array} array A multi dimensional array
* @return {Array} The flattened array (1 dimensional)
*/
export function flatten(array) {
if (!Array.isArray(array)) {
// if not an array, return as is
return array;
}
var flat = [];
array.forEach(function callback(value) {
if (Array.isArray(value)) {
value.forEach(callback); // traverse through sub-arrays recursively
} else {
flat.push(value);
}
});
return flat;
}
/**
* A safe map
* @param {Array} array
* @param {function} callback
*/
export function map(array, callback) {
return Array.prototype.map.call(array, callback);
}
/**
* A safe forEach
* @param {Array} array
* @param {function} callback
*/
export function forEach(array, callback) {
Array.prototype.forEach.call(array, callback);
}
/**
* A safe filter
* @param {Array} array
* @param {function} callback
*/
export function filter(array, callback) {
if (arraySize(array).length !== 1) {
throw new Error('Only one dimensional matrices supported');
}
return Array.prototype.filter.call(array, callback);
}
/**
* Filter values in a callback given a regular expression
* @param {Array} array
* @param {RegExp} regexp
* @return {Array} Returns the filtered array
* @private
*/
export function filterRegExp(array, regexp) {
if (arraySize(array).length !== 1) {
throw new Error('Only one dimensional matrices supported');
}
return Array.prototype.filter.call(array, entry => regexp.test(entry));
}
/**
* A safe join
* @param {Array} array
* @param {string} separator
*/
export function join(array, separator) {
return Array.prototype.join.call(array, separator);
}
/**
* Assign a numeric identifier to every element of a sorted array
* @param {Array} a An array
* @return {Array} An array of objects containing the original value and its identifier
*/
export function identify(a) {
if (!Array.isArray(a)) {
throw new TypeError('Array input expected');
}
if (a.length === 0) {
return a;
}
var b = [];
var count = 0;
b[0] = {
value: a[0],
identifier: 0
};
for (var i = 1; i < a.length; i++) {
if (a[i] === a[i - 1]) {
count++;
} else {
count = 0;
}
b.push({
value: a[i],
identifier: count
});
}
return b;
}
/**
* Remove the numeric identifier from the elements
* @param {array} a An array
* @return {array} An array of values without identifiers
*/
export function generalize(a) {
if (!Array.isArray(a)) {
throw new TypeError('Array input expected');
}
if (a.length === 0) {
return a;
}
var b = [];
for (var i = 0; i < a.length; i++) {
b.push(a[i].value);
}
return b;
}
/**
* Check the datatype of a given object
* This is a low level implementation that should only be used by
* parent Matrix classes such as SparseMatrix or DenseMatrix
* This method does not validate Array Matrix shape
* @param {Array} array
* @param {function} typeOf Callback function to use to determine the type of a value
* @return {string}
*/
export function getArrayDataType(array, typeOf) {
var type; // to hold type info
var length = 0; // to hold length value to ensure it has consistent sizes
for (var i = 0; i < array.length; i++) {
var item = array[i];
var _isArray = Array.isArray(item);
// Saving the target matrix row size
if (i === 0 && _isArray) {
length = item.length;
}
// If the current item is an array but the length does not equal the targetVectorSize
if (_isArray && item.length !== length) {
return undefined;
}
var itemType = _isArray ? getArrayDataType(item, typeOf) // recurse into a nested array
: typeOf(item);
if (type === undefined) {
type = itemType; // first item
} else if (type !== itemType) {
return 'mixed';
} else {
// we're good, everything has the same type so far
}
}
return type;
}
/**
* Return the last item from an array
* @param {array}
* @returns {*}
*/
export function last(array) {
return array[array.length - 1];
}
/**
* Get all but the last element of array.
* @param {array}
* @returns {*}
*/
export function initial(array) {
return array.slice(0, array.length - 1);
}
/**
* Recursively concatenate two matrices.
* The contents of the matrices is not cloned.
* @param {Array} a Multi dimensional array
* @param {Array} b Multi dimensional array
* @param {number} concatDim The dimension on which to concatenate (zero-based)
* @param {number} dim The current dim (zero-based)
* @return {Array} c The concatenated matrix
* @private
*/
function concatRecursive(a, b, concatDim, dim) {
if (dim < concatDim) {
// recurse into next dimension
if (a.length !== b.length) {
throw new DimensionError(a.length, b.length);
}
var c = [];
for (var i = 0; i < a.length; i++) {
c[i] = concatRecursive(a[i], b[i], concatDim, dim + 1);
}
return c;
} else {
// concatenate this dimension
return a.concat(b);
}
}
/**
* Concatenates many arrays in the specified direction
* @param {...Array} arrays All the arrays to concatenate
* @param {number} concatDim The dimension on which to concatenate (zero-based)
* @returns
*/
export function concat() {
var arrays = Array.prototype.slice.call(arguments, 0, -1);
var concatDim = Array.prototype.slice.call(arguments, -1);
if (arrays.length === 1) {
return arrays[0];
}
if (arrays.length > 1) {
return arrays.slice(1).reduce(function (A, B) {
return concatRecursive(A, B, concatDim, 0);
}, arrays[0]);
} else {
throw new Error('Wrong number of arguments in function concat');
}
}
/**
* Receives two or more sizes and get's the broadcasted size for both.
* @param {...number[]} sizes Sizes to broadcast together
* @returns
*/
export function broadcastSizes() {
for (var _len = arguments.length, sizes = new Array(_len), _key = 0; _key < _len; _key++) {
sizes[_key] = arguments[_key];
}
var dimensions = sizes.map(s => s.length);
var N = Math.max(...dimensions);
var sizeMax = new Array(N).fill(null);
// check for every size
for (var i = 0; i < sizes.length; i++) {
var size = sizes[i];
var dim = dimensions[i];
for (var j = 0; j < dim; j++) {
var n = N - dim + j;
if (size[j] > sizeMax[n]) {
sizeMax[n] = size[j];
}
}
}
for (var _i = 0; _i < sizes.length; _i++) {
checkBroadcastingRules(sizes[_i], sizeMax);
}
return sizeMax;
}
/**
* Checks if it's possible to broadcast a size to another size
* @param {number[]} size The size of the array to check
* @param {number[]} toSize The size of the array to validate if it can be broadcasted to
*/
export function checkBroadcastingRules(size, toSize) {
var N = toSize.length;
var dim = size.length;
for (var j = 0; j < dim; j++) {
var n = N - dim + j;
if (size[j] < toSize[n] && size[j] > 1 || size[j] > toSize[n]) {
throw new Error("shape missmatch: missmatch is found in arg with shape (".concat(size, ") not possible to broadcast dimension ").concat(dim, " with size ").concat(size[j], " to size ").concat(toSize[n]));
}
}
}
/**
* Broadcasts a single array to a certain size
* @param {array} array Array to be broadcasted
* @param {number[]} toSize Size to broadcast the array
* @returns The broadcasted array
*/
export function broadcastTo(array, toSize) {
var Asize = arraySize(array);
if (deepStrictEqual(Asize, toSize)) {
return array;
}
checkBroadcastingRules(Asize, toSize);
var broadcastedSize = broadcastSizes(Asize, toSize);
var N = broadcastedSize.length;
var paddedSize = [...Array(N - Asize.length).fill(1), ...Asize];
var A = clone(array);
// reshape A if needed to make it ready for concat
if (Asize.length < N) {
A = reshape(A, paddedSize);
Asize = arraySize(A);
}
// stretches the array on each dimension to make it the same size as index
for (var dim = 0; dim < N; dim++) {
if (Asize[dim] < broadcastedSize[dim]) {
A = stretch(A, broadcastedSize[dim], dim);
Asize = arraySize(A);
}
}
return A;
}
/**
* Broadcasts arrays and returns the broadcasted arrays in an array
* @param {...Array | any} arrays
* @returns
*/
export function broadcastArrays() {
for (var _len2 = arguments.length, arrays = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
arrays[_key2] = arguments[_key2];
}
if (arrays.length === 0) {
throw new Error('Insuficient number of argumnets in function broadcastArrays');
}
if (arrays.length === 1) {
return arrays[0];
}
var sizes = arrays.map(function (array) {
return arraySize(array);
});
var broadcastedSize = broadcastSizes(...sizes);
var broadcastedArrays = [];
arrays.forEach(function (array) {
broadcastedArrays.push(broadcastTo(array, broadcastedSize));
});
return broadcastedArrays;
}
/**
* stretches a matrix up to a certain size in a certain dimension
* @param {Array} arrayToStretch
* @param {number[]} sizeToStretch
* @param {number} dimToStretch
* @returns
*/
export function stretch(arrayToStretch, sizeToStretch, dimToStretch) {
return concat(...Array(sizeToStretch).fill(arrayToStretch), dimToStretch);
}
/**
* Retrieves a single element from an array given an index.
*
* @param {Array} array - The array from which to retrieve the value.
* @param {Array<number>} idx - An array of indices specifying the position of the desired element in each dimension.
* @returns {*} - The value at the specified position in the array.
*
* @example
* const arr = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
* const index = [1, 0, 1];
* console.log(getValue(arr, index)); // 6
*/
export function get(array, index) {
if (!Array.isArray(array)) {
throw new Error('Array expected');
}
var size = arraySize(array);
if (index.length !== size.length) {
throw new DimensionError(index.length, size.length);
}
for (var x = 0; x < index.length; x++) {
validateIndex(index[x], size[x]);
}
return index.reduce((acc, curr) => acc[curr], array);
}
/**
* Recursive function to map a multi-dimensional array.
*
* @param {*} value - The current value being processed in the array.
* @param {Array} index - The index of the current value being processed in the array.
* @param {Array} array - The array being processed.
* @param {Function} callback - Function that produces the element of the new Array, taking three arguments: the value of the element, the index of the element, and the Array being processed.
* @returns {*} The new array with each element being the result of the callback function.
*/
export function recurse(value, index, array, callback) {
if (Array.isArray(value)) {
return value.map(function (child, i) {
// we create a copy of the index array and append the new index value
return recurse(child, index.concat(i), array, callback);
});
} else {
// invoke the callback function with the right number of arguments
return callback(value, index, array);
}
}
/**
* Deep clones a multidimensional array
* @param {Array} array
* @returns cloned array
*/
export function clone(array) {
return _extends([], array);
}

399
node_modules/mathjs/lib/esm/utils/bignumber/bitwise.js generated vendored Normal file
View File

@@ -0,0 +1,399 @@
/**
* Bitwise and for Bignumbers
*
* Special Cases:
* N & n = N
* n & 0 = 0
* n & -1 = n
* n & n = n
* I & I = I
* -I & -I = -I
* I & -I = 0
* I & n = n
* I & -n = I
* -I & n = 0
* -I & -n = -I
*
* @param {BigNumber} x
* @param {BigNumber} y
* @return {BigNumber} Result of `x` & `y`, is fully precise
* @private
*/
export function bitAndBigNumber(x, y) {
if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
throw new Error('Integers expected in function bitAnd');
}
var BigNumber = x.constructor;
if (x.isNaN() || y.isNaN()) {
return new BigNumber(NaN);
}
if (x.isZero() || y.eq(-1) || x.eq(y)) {
return x;
}
if (y.isZero() || x.eq(-1)) {
return y;
}
if (!x.isFinite() || !y.isFinite()) {
if (!x.isFinite() && !y.isFinite()) {
if (x.isNegative() === y.isNegative()) {
return x;
}
return new BigNumber(0);
}
if (!x.isFinite()) {
if (y.isNegative()) {
return x;
}
if (x.isNegative()) {
return new BigNumber(0);
}
return y;
}
if (!y.isFinite()) {
if (x.isNegative()) {
return y;
}
if (y.isNegative()) {
return new BigNumber(0);
}
return x;
}
}
return bitwise(x, y, function (a, b) {
return a & b;
});
}
/**
* Bitwise not
* @param {BigNumber} x
* @return {BigNumber} Result of ~`x`, fully precise
*
*/
export function bitNotBigNumber(x) {
if (x.isFinite() && !x.isInteger()) {
throw new Error('Integer expected in function bitNot');
}
var BigNumber = x.constructor;
var prevPrec = BigNumber.precision;
BigNumber.config({
precision: 1E9
});
var result = x.plus(new BigNumber(1));
result.s = -result.s || null;
BigNumber.config({
precision: prevPrec
});
return result;
}
/**
* Bitwise OR for BigNumbers
*
* Special Cases:
* N | n = N
* n | 0 = n
* n | -1 = -1
* n | n = n
* I | I = I
* -I | -I = -I
* I | -n = -1
* I | -I = -1
* I | n = I
* -I | n = -I
* -I | -n = -n
*
* @param {BigNumber} x
* @param {BigNumber} y
* @return {BigNumber} Result of `x` | `y`, fully precise
*/
export function bitOrBigNumber(x, y) {
if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
throw new Error('Integers expected in function bitOr');
}
var BigNumber = x.constructor;
if (x.isNaN() || y.isNaN()) {
return new BigNumber(NaN);
}
var negOne = new BigNumber(-1);
if (x.isZero() || y.eq(negOne) || x.eq(y)) {
return y;
}
if (y.isZero() || x.eq(negOne)) {
return x;
}
if (!x.isFinite() || !y.isFinite()) {
if (!x.isFinite() && !x.isNegative() && y.isNegative() || x.isNegative() && !y.isNegative() && !y.isFinite()) {
return negOne;
}
if (x.isNegative() && y.isNegative()) {
return x.isFinite() ? x : y;
}
return x.isFinite() ? y : x;
}
return bitwise(x, y, function (a, b) {
return a | b;
});
}
/**
* Applies bitwise function to numbers
* @param {BigNumber} x
* @param {BigNumber} y
* @param {function (a, b)} func
* @return {BigNumber}
*/
export function bitwise(x, y, func) {
var BigNumber = x.constructor;
var xBits, yBits;
var xSign = +(x.s < 0);
var ySign = +(y.s < 0);
if (xSign) {
xBits = decCoefficientToBinaryString(bitNotBigNumber(x));
for (var i = 0; i < xBits.length; ++i) {
xBits[i] ^= 1;
}
} else {
xBits = decCoefficientToBinaryString(x);
}
if (ySign) {
yBits = decCoefficientToBinaryString(bitNotBigNumber(y));
for (var _i = 0; _i < yBits.length; ++_i) {
yBits[_i] ^= 1;
}
} else {
yBits = decCoefficientToBinaryString(y);
}
var minBits, maxBits, minSign;
if (xBits.length <= yBits.length) {
minBits = xBits;
maxBits = yBits;
minSign = xSign;
} else {
minBits = yBits;
maxBits = xBits;
minSign = ySign;
}
var shortLen = minBits.length;
var longLen = maxBits.length;
var expFuncVal = func(xSign, ySign) ^ 1;
var outVal = new BigNumber(expFuncVal ^ 1);
var twoPower = new BigNumber(1);
var two = new BigNumber(2);
var prevPrec = BigNumber.precision;
BigNumber.config({
precision: 1E9
});
while (shortLen > 0) {
if (func(minBits[--shortLen], maxBits[--longLen]) === expFuncVal) {
outVal = outVal.plus(twoPower);
}
twoPower = twoPower.times(two);
}
while (longLen > 0) {
if (func(minSign, maxBits[--longLen]) === expFuncVal) {
outVal = outVal.plus(twoPower);
}
twoPower = twoPower.times(two);
}
BigNumber.config({
precision: prevPrec
});
if (expFuncVal === 0) {
outVal.s = -outVal.s;
}
return outVal;
}
/* Extracted from decimal.js, and edited to specialize. */
function decCoefficientToBinaryString(x) {
// Convert to string
var a = x.d; // array with digits
var r = a[0] + '';
for (var i = 1; i < a.length; ++i) {
var s = a[i] + '';
for (var z = 7 - s.length; z--;) {
s = '0' + s;
}
r += s;
}
var j = r.length;
while (r.charAt(j) === '0') {
j--;
}
var xe = x.e;
var str = r.slice(0, j + 1 || 1);
var strL = str.length;
if (xe > 0) {
if (++xe > strL) {
// Append zeros.
xe -= strL;
while (xe--) {
str += '0';
}
} else if (xe < strL) {
str = str.slice(0, xe) + '.' + str.slice(xe);
}
}
// Convert from base 10 (decimal) to base 2
var arr = [0];
for (var _i2 = 0; _i2 < str.length;) {
var arrL = arr.length;
while (arrL--) {
arr[arrL] *= 10;
}
arr[0] += parseInt(str.charAt(_i2++)); // convert to int
for (var _j = 0; _j < arr.length; ++_j) {
if (arr[_j] > 1) {
if (arr[_j + 1] === null || arr[_j + 1] === undefined) {
arr[_j + 1] = 0;
}
arr[_j + 1] += arr[_j] >> 1;
arr[_j] &= 1;
}
}
}
return arr.reverse();
}
/**
* Bitwise XOR for BigNumbers
*
* Special Cases:
* N ^ n = N
* n ^ 0 = n
* n ^ n = 0
* n ^ -1 = ~n
* I ^ n = I
* I ^ -n = -I
* I ^ -I = -1
* -I ^ n = -I
* -I ^ -n = I
*
* @param {BigNumber} x
* @param {BigNumber} y
* @return {BigNumber} Result of `x` ^ `y`, fully precise
*
*/
export function bitXor(x, y) {
if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
throw new Error('Integers expected in function bitXor');
}
var BigNumber = x.constructor;
if (x.isNaN() || y.isNaN()) {
return new BigNumber(NaN);
}
if (x.isZero()) {
return y;
}
if (y.isZero()) {
return x;
}
if (x.eq(y)) {
return new BigNumber(0);
}
var negOne = new BigNumber(-1);
if (x.eq(negOne)) {
return bitNotBigNumber(y);
}
if (y.eq(negOne)) {
return bitNotBigNumber(x);
}
if (!x.isFinite() || !y.isFinite()) {
if (!x.isFinite() && !y.isFinite()) {
return negOne;
}
return new BigNumber(x.isNegative() === y.isNegative() ? Infinity : -Infinity);
}
return bitwise(x, y, function (a, b) {
return a ^ b;
});
}
/**
* Bitwise left shift
*
* Special Cases:
* n << -n = N
* n << N = N
* N << n = N
* n << 0 = n
* 0 << n = 0
* I << I = N
* I << n = I
* n << I = I
*
* @param {BigNumber} x
* @param {BigNumber} y
* @return {BigNumber} Result of `x` << `y`
*
*/
export function leftShiftBigNumber(x, y) {
if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
throw new Error('Integers expected in function leftShift');
}
var BigNumber = x.constructor;
if (x.isNaN() || y.isNaN() || y.isNegative() && !y.isZero()) {
return new BigNumber(NaN);
}
if (x.isZero() || y.isZero()) {
return x;
}
if (!x.isFinite() && !y.isFinite()) {
return new BigNumber(NaN);
}
// Math.pow(2, y) is fully precise for y < 55, and fast
if (y.lt(55)) {
return x.times(Math.pow(2, y.toNumber()) + '');
}
return x.times(new BigNumber(2).pow(y));
}
/*
* Special Cases:
* n >> -n = N
* n >> N = N
* N >> n = N
* I >> I = N
* n >> 0 = n
* I >> n = I
* -I >> n = -I
* -I >> I = -I
* n >> I = I
* -n >> I = -1
* 0 >> n = 0
*
* @param {BigNumber} value
* @param {BigNumber} value
* @return {BigNumber} Result of `x` >> `y`
*
*/
export function rightArithShiftBigNumber(x, y) {
if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
throw new Error('Integers expected in function rightArithShift');
}
var BigNumber = x.constructor;
if (x.isNaN() || y.isNaN() || y.isNegative() && !y.isZero()) {
return new BigNumber(NaN);
}
if (x.isZero() || y.isZero()) {
return x;
}
if (!y.isFinite()) {
if (x.isNegative()) {
return new BigNumber(-1);
}
if (!x.isFinite()) {
return new BigNumber(NaN);
}
return new BigNumber(0);
}
// Math.pow(2, y) is fully precise for y < 55, and fast
if (y.lt(55)) {
return x.div(Math.pow(2, y.toNumber()) + '').floor();
}
return x.div(new BigNumber(2).pow(y)).floor();
}

View File

@@ -0,0 +1,57 @@
import { memoize } from '../function.js';
/**
* Calculate BigNumber e
* @param {function} BigNumber BigNumber constructor
* @returns {BigNumber} Returns e
*/
export var createBigNumberE = memoize(function (BigNumber) {
return new BigNumber(1).exp();
}, {
hasher
});
/**
* Calculate BigNumber golden ratio, phi = (1+sqrt(5))/2
* @param {function} BigNumber BigNumber constructor
* @returns {BigNumber} Returns phi
*/
export var createBigNumberPhi = memoize(function (BigNumber) {
return new BigNumber(1).plus(new BigNumber(5).sqrt()).div(2);
}, {
hasher
});
/**
* Calculate BigNumber pi.
* @param {function} BigNumber BigNumber constructor
* @returns {BigNumber} Returns pi
*/
export var createBigNumberPi = memoize(function (BigNumber) {
return BigNumber.acos(-1);
}, {
hasher
});
/**
* Calculate BigNumber tau, tau = 2 * pi
* @param {function} BigNumber BigNumber constructor
* @returns {BigNumber} Returns tau
*/
export var createBigNumberTau = memoize(function (BigNumber) {
return createBigNumberPi(BigNumber).times(2);
}, {
hasher
});
/**
* Create a hash for a BigNumber constructor function. The created has is
* the configured precision
* @param {Array} args Supposed to contain a single entry with
* a BigNumber constructor
* @return {number} precision
* @private
*/
function hasher(args) {
return args[0].precision;
}

View File

@@ -0,0 +1,243 @@
import { isBigNumber, isNumber } from '../is.js';
import { isInteger, normalizeFormatOptions } from '../number.js';
/**
* Formats a BigNumber in a given base
* @param {BigNumber} n
* @param {number} base
* @param {number} size
* @returns {string}
*/
function formatBigNumberToBase(n, base, size) {
var BigNumberCtor = n.constructor;
var big2 = new BigNumberCtor(2);
var suffix = '';
if (size) {
if (size < 1) {
throw new Error('size must be in greater than 0');
}
if (!isInteger(size)) {
throw new Error('size must be an integer');
}
if (n.greaterThan(big2.pow(size - 1).sub(1)) || n.lessThan(big2.pow(size - 1).mul(-1))) {
throw new Error("Value must be in range [-2^".concat(size - 1, ", 2^").concat(size - 1, "-1]"));
}
if (!n.isInteger()) {
throw new Error('Value must be an integer');
}
if (n.lessThan(0)) {
n = n.add(big2.pow(size));
}
suffix = "i".concat(size);
}
switch (base) {
case 2:
return "".concat(n.toBinary()).concat(suffix);
case 8:
return "".concat(n.toOctal()).concat(suffix);
case 16:
return "".concat(n.toHexadecimal()).concat(suffix);
default:
throw new Error("Base ".concat(base, " not supported "));
}
}
/**
* Convert a BigNumber to a formatted string representation.
*
* Syntax:
*
* format(value)
* format(value, options)
* format(value, precision)
* format(value, fn)
*
* Where:
*
* {number} value The value to be formatted
* {Object} options An object with formatting options. Available options:
* {string} notation
* Number notation. Choose from:
* 'fixed' Always use regular number notation.
* For example '123.40' and '14000000'
* 'exponential' Always use exponential notation.
* For example '1.234e+2' and '1.4e+7'
* 'auto' (default) Regular number notation for numbers
* having an absolute value between
* `lower` and `upper` bounds, and uses
* exponential notation elsewhere.
* Lower bound is included, upper bound
* is excluded.
* For example '123.4' and '1.4e7'.
* 'bin', 'oct, or
* 'hex' Format the number using binary, octal,
* or hexadecimal notation.
* For example '0b1101' and '0x10fe'.
* {number} wordSize The word size in bits to use for formatting
* in binary, octal, or hexadecimal notation.
* To be used only with 'bin', 'oct', or 'hex'
* values for 'notation' option. When this option
* is defined the value is formatted as a signed
* twos complement integer of the given word size
* and the size suffix is appended to the output.
* For example
* format(-1, {notation: 'hex', wordSize: 8}) === '0xffi8'.
* Default value is undefined.
* {number} precision A number between 0 and 16 to round
* the digits of the number.
* In case of notations 'exponential',
* 'engineering', and 'auto',
* `precision` defines the total
* number of significant digits returned.
* In case of notation 'fixed',
* `precision` defines the number of
* significant digits after the decimal
* point.
* `precision` is undefined by default.
* {number} lowerExp Exponent determining the lower boundary
* for formatting a value with an exponent
* when `notation='auto`.
* Default value is `-3`.
* {number} upperExp Exponent determining the upper boundary
* for formatting a value with an exponent
* when `notation='auto`.
* Default value is `5`.
* {Function} fn A custom formatting function. Can be used to override the
* built-in notations. Function `fn` is called with `value` as
* parameter and must return a string. Is useful for example to
* format all values inside a matrix in a particular way.
*
* Examples:
*
* format(6.4) // '6.4'
* format(1240000) // '1.24e6'
* format(1/3) // '0.3333333333333333'
* format(1/3, 3) // '0.333'
* format(21385, 2) // '21000'
* format(12e8, {notation: 'fixed'}) // returns '1200000000'
* format(2.3, {notation: 'fixed', precision: 4}) // returns '2.3000'
* format(52.8, {notation: 'exponential'}) // returns '5.28e+1'
* format(12400, {notation: 'engineering'}) // returns '12.400e+3'
*
* @param {BigNumber} value
* @param {Object | Function | number | BigNumber} [options]
* @return {string} str The formatted value
*/
export function format(value, options) {
if (typeof options === 'function') {
// handle format(value, fn)
return options(value);
}
// handle special cases
if (!value.isFinite()) {
return value.isNaN() ? 'NaN' : value.gt(0) ? 'Infinity' : '-Infinity';
}
var {
notation,
precision,
wordSize
} = normalizeFormatOptions(options);
// handle the various notations
switch (notation) {
case 'fixed':
return toFixed(value, precision);
case 'exponential':
return toExponential(value, precision);
case 'engineering':
return toEngineering(value, precision);
case 'bin':
return formatBigNumberToBase(value, 2, wordSize);
case 'oct':
return formatBigNumberToBase(value, 8, wordSize);
case 'hex':
return formatBigNumberToBase(value, 16, wordSize);
case 'auto':
{
// determine lower and upper bound for exponential notation.
// TODO: implement support for upper and lower to be BigNumbers themselves
var lowerExp = _toNumberOrDefault(options === null || options === void 0 ? void 0 : options.lowerExp, -3);
var upperExp = _toNumberOrDefault(options === null || options === void 0 ? void 0 : options.upperExp, 5);
// handle special case zero
if (value.isZero()) return '0';
// determine whether or not to output exponential notation
var str;
var rounded = value.toSignificantDigits(precision);
var exp = rounded.e;
if (exp >= lowerExp && exp < upperExp) {
// normal number notation
str = rounded.toFixed();
} else {
// exponential notation
str = toExponential(value, precision);
}
// remove trailing zeros after the decimal point
return str.replace(/((\.\d*?)(0+))($|e)/, function () {
var digits = arguments[2];
var e = arguments[4];
return digits !== '.' ? digits + e : e;
});
}
default:
throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.');
}
}
/**
* Format a BigNumber in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3'
* @param {BigNumber} value
* @param {number} [precision] Optional number of significant figures to return.
*/
export function toEngineering(value, precision) {
// find nearest lower multiple of 3 for exponent
var e = value.e;
var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3;
// find difference in exponents, and calculate the value without exponent
var valueWithoutExp = value.mul(Math.pow(10, -newExp));
var valueStr = valueWithoutExp.toPrecision(precision);
if (valueStr.includes('e')) {
var BigNumber = value.constructor;
valueStr = new BigNumber(valueStr).toFixed();
}
return valueStr + 'e' + (e >= 0 ? '+' : '') + newExp.toString();
}
/**
* Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3'
* @param {BigNumber} value
* @param {number} [precision] Number of digits in formatted output.
* If not provided, the maximum available digits
* is used.
* @returns {string} str
*/
export function toExponential(value, precision) {
if (precision !== undefined) {
return value.toExponential(precision - 1); // Note the offset of one
} else {
return value.toExponential();
}
}
/**
* Format a number with fixed notation.
* @param {BigNumber} value
* @param {number} [precision=undefined] Optional number of decimals after the
* decimal point. Undefined by default.
*/
export function toFixed(value, precision) {
return value.toFixed(precision);
}
function _toNumberOrDefault(value, defaultValue) {
if (isNumber(value)) {
return value;
} else if (isBigNumber(value)) {
return value.toNumber();
} else {
return defaultValue;
}
}

View File

@@ -0,0 +1,39 @@
/**
* Compares two BigNumbers.
* @param {BigNumber} a - First value to compare
* @param {BigNumber} b - Second value to compare
* @param {number} [relTol=1e-09] - The relative tolerance, indicating the maximum allowed difference relative to the larger absolute value. Must be greater than 0.
* @param {number} [absTol=0] - The minimum absolute tolerance, useful for comparisons near zero. Must be at least 0.
* @returns {boolean} whether the two numbers are nearly equal
* @throws {Error} If `relTol` is less than or equal to 0.
* @throws {Error} If `absTol` is less than 0.
*
* @example
* nearlyEqual(1.000000001, 1.0, 1e-9); // true
* nearlyEqual(1.000000002, 1.0, 0); // false
* nearlyEqual(1.0, 1.009, undefined, 0.02); // true
* nearlyEqual(0.000000001, 0.0, undefined, 1e-8); // true
*/
export function nearlyEqual(a, b) {
var relTol = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1e-9;
var absTol = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
if (relTol <= 0) {
throw new Error('Relative tolerance must be greater than 0');
}
if (absTol < 0) {
throw new Error('Absolute tolerance must be at least 0');
}
// NaN
if (a.isNaN() || b.isNaN()) {
return false;
}
if (!a.isFinite() || !b.isFinite()) {
return a.eq(b);
}
// use "==" operator, handles infinities
if (a.eq(b)) {
return true;
}
// abs(a-b) <= max(relTol * max(abs(a), abs(b)), absTol)
return a.minus(b).abs().lte(a.constructor.max(a.constructor.max(a.abs(), b.abs()).mul(relTol), absTol));
}

177
node_modules/mathjs/lib/esm/utils/collection.js generated vendored Normal file
View File

@@ -0,0 +1,177 @@
import { isCollection, isMatrix } from './is.js';
import { IndexError } from '../error/IndexError.js';
import { arraySize } from './array.js';
import { _switch } from './switch.js';
/**
* Test whether an array contains collections
* @param {Array} array
* @returns {boolean} Returns true when the array contains one or multiple
* collections (Arrays or Matrices). Returns false otherwise.
*/
export function containsCollections(array) {
for (var i = 0; i < array.length; i++) {
if (isCollection(array[i])) {
return true;
}
}
return false;
}
/**
* Recursively loop over all elements in a given multi dimensional array
* and invoke the callback on each of the elements.
* @param {Array | Matrix} array
* @param {Function} callback The callback method is invoked with one
* parameter: the current element in the array
*/
export function deepForEach(array, callback) {
if (isMatrix(array)) {
array = array.valueOf();
}
for (var i = 0, ii = array.length; i < ii; i++) {
var value = array[i];
if (Array.isArray(value)) {
deepForEach(value, callback);
} else {
callback(value);
}
}
}
/**
* Execute the callback function element wise for each element in array and any
* nested array
* Returns an array with the results
* @param {Array | Matrix} array
* @param {Function} callback The callback is called with two parameters:
* value1 and value2, which contain the current
* element of both arrays.
* @param {boolean} [skipZeros] Invoke callback function for non-zero values only.
*
* @return {Array | Matrix} res
*/
export function deepMap(array, callback, skipZeros) {
if (array && typeof array.map === 'function') {
// TODO: replace array.map with a for loop to improve performance
return array.map(function (x) {
return deepMap(x, callback, skipZeros);
});
} else {
return callback(array);
}
}
/**
* Reduce a given matrix or array to a new matrix or
* array with one less dimension, applying the given
* callback in the selected dimension.
* @param {Array | Matrix} mat
* @param {number} dim
* @param {Function} callback
* @return {Array | Matrix} res
*/
export function reduce(mat, dim, callback) {
var size = Array.isArray(mat) ? arraySize(mat) : mat.size();
if (dim < 0 || dim >= size.length) {
// TODO: would be more clear when throwing a DimensionError here
throw new IndexError(dim, size.length);
}
if (isMatrix(mat)) {
return mat.create(_reduce(mat.valueOf(), dim, callback), mat.datatype());
} else {
return _reduce(mat, dim, callback);
}
}
/**
* Recursively reduce a matrix
* @param {Array} mat
* @param {number} dim
* @param {Function} callback
* @returns {Array} ret
* @private
*/
function _reduce(mat, dim, callback) {
var i, ret, val, tran;
if (dim <= 0) {
if (!Array.isArray(mat[0])) {
val = mat[0];
for (i = 1; i < mat.length; i++) {
val = callback(val, mat[i]);
}
return val;
} else {
tran = _switch(mat);
ret = [];
for (i = 0; i < tran.length; i++) {
ret[i] = _reduce(tran[i], dim - 1, callback);
}
return ret;
}
} else {
ret = [];
for (i = 0; i < mat.length; i++) {
ret[i] = _reduce(mat[i], dim - 1, callback);
}
return ret;
}
}
// TODO: document function scatter
export function scatter(a, j, w, x, u, mark, cindex, f, inverse, update, value) {
// a arrays
var avalues = a._values;
var aindex = a._index;
var aptr = a._ptr;
// vars
var k, k0, k1, i;
// check we need to process values (pattern matrix)
if (x) {
// values in j
for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
// row
i = aindex[k];
// check value exists in current j
if (w[i] !== mark) {
// i is new entry in j
w[i] = mark;
// add i to pattern of C
cindex.push(i);
// x(i) = A, check we need to call function this time
if (update) {
// copy value to workspace calling callback function
x[i] = inverse ? f(avalues[k], value) : f(value, avalues[k]);
// function was called on current row
u[i] = mark;
} else {
// copy value to workspace
x[i] = avalues[k];
}
} else {
// i exists in C already
x[i] = inverse ? f(avalues[k], x[i]) : f(x[i], avalues[k]);
// function was called on current row
u[i] = mark;
}
}
} else {
// values in j
for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
// row
i = aindex[k];
// check value exists in current j
if (w[i] !== mark) {
// i is new entry in j
w[i] = mark;
// add i to pattern of C
cindex.push(i);
} else {
// indicate function was called on current row
u[i] = mark;
}
}
}
}

14
node_modules/mathjs/lib/esm/utils/complex.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import { nearlyEqual } from './number.js';
/**
* Test whether two complex values are equal provided a given relTol and absTol.
* Does not use or change the global Complex.EPSILON setting
* @param {Complex} x - The first complex number for comparison.
* @param {Complex} y - The second complex number for comparison.
* @param {number} relTol - The relative tolerance for comparison.
* @param {number} absTol - The absolute tolerance for comparison.
* @returns {boolean} - Returns true if the two complex numbers are equal within the given tolerances, otherwise returns false.
*/
export function complexEquals(x, y, relTol, absTol) {
return nearlyEqual(x.re, y.re, relTol, absTol) && nearlyEqual(x.im, y.im, relTol, absTol);
}

147
node_modules/mathjs/lib/esm/utils/customs.js generated vendored Normal file
View File

@@ -0,0 +1,147 @@
import { hasOwnProperty } from './object.js';
/**
* Get a property of a plain object
* Throws an error in case the object is not a plain object or the
* property is not defined on the object itself
* @param {Object} object
* @param {string} prop
* @return {*} Returns the property value when safe
*/
function getSafeProperty(object, prop) {
// only allow getting safe properties of a plain object
if (isSafeProperty(object, prop)) {
return object[prop];
}
if (typeof object[prop] === 'function' && isSafeMethod(object, prop)) {
throw new Error('Cannot access method "' + prop + '" as a property');
}
throw new Error('No access to property "' + prop + '"');
}
/**
* Set a property on a plain object.
* Throws an error in case the object is not a plain object or the
* property would override an inherited property like .constructor or .toString
* @param {Object} object
* @param {string} prop
* @param {*} value
* @return {*} Returns the value
*/
// TODO: merge this function into access.js?
function setSafeProperty(object, prop, value) {
// only allow setting safe properties of a plain object
if (isSafeProperty(object, prop)) {
object[prop] = value;
return value;
}
throw new Error('No access to property "' + prop + '"');
}
/**
* Test whether a property is safe to use on an object or Array.
* For example .toString and .constructor are not safe
* @param {Object | Array} object
* @param {string} prop
* @return {boolean} Returns true when safe
*/
function isSafeProperty(object, prop) {
if (!isPlainObject(object) && !Array.isArray(object)) {
return false;
}
// SAFE: whitelisted
// e.g length
if (hasOwnProperty(safeNativeProperties, prop)) {
return true;
}
// UNSAFE: inherited from Object prototype
// e.g constructor
if (prop in Object.prototype) {
// 'in' is used instead of hasOwnProperty for nodejs v0.10
// which is inconsistent on root prototypes. It is safe
// here because Object.prototype is a root object
return false;
}
// UNSAFE: inherited from Function prototype
// e.g call, apply
if (prop in Function.prototype) {
// 'in' is used instead of hasOwnProperty for nodejs v0.10
// which is inconsistent on root prototypes. It is safe
// here because Function.prototype is a root object
return false;
}
return true;
}
/**
* Validate whether a method is safe.
* Throws an error when that's not the case.
* @param {Object} object
* @param {string} method
* @return {function} Returns the method when valid
*/
function getSafeMethod(object, method) {
if (!isSafeMethod(object, method)) {
throw new Error('No access to method "' + method + '"');
}
return object[method];
}
/**
* Check whether a method is safe.
* Throws an error when that's not the case (for example for `constructor`).
* @param {Object} object
* @param {string} method
* @return {boolean} Returns true when safe, false otherwise
*/
function isSafeMethod(object, method) {
if (object === null || object === undefined || typeof object[method] !== 'function') {
return false;
}
// UNSAFE: ghosted
// e.g overridden toString
// Note that IE10 doesn't support __proto__ and we can't do this check there.
if (hasOwnProperty(object, method) && Object.getPrototypeOf && method in Object.getPrototypeOf(object)) {
return false;
}
// SAFE: whitelisted
// e.g toString
if (hasOwnProperty(safeNativeMethods, method)) {
return true;
}
// UNSAFE: inherited from Object prototype
// e.g constructor
if (method in Object.prototype) {
// 'in' is used instead of hasOwnProperty for nodejs v0.10
// which is inconsistent on root prototypes. It is safe
// here because Object.prototype is a root object
return false;
}
// UNSAFE: inherited from Function prototype
// e.g call, apply
if (method in Function.prototype) {
// 'in' is used instead of hasOwnProperty for nodejs v0.10
// which is inconsistent on root prototypes. It is safe
// here because Function.prototype is a root object
return false;
}
return true;
}
function isPlainObject(object) {
return typeof object === 'object' && object && object.constructor === Object;
}
var safeNativeProperties = {
length: true,
name: true
};
var safeNativeMethods = {
toString: true,
valueOf: true,
toLocaleString: true
};
export { getSafeProperty };
export { setSafeProperty };
export { isSafeProperty };
export { getSafeMethod };
export { isSafeMethod };
export { isPlainObject };

18
node_modules/mathjs/lib/esm/utils/emitter.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
import Emitter from 'tiny-emitter';
/**
* Extend given object with emitter functions `on`, `off`, `once`, `emit`
* @param {Object} obj
* @return {Object} obj
*/
export function mixin(obj) {
// create event emitter
var emitter = new Emitter();
// bind methods to obj (we don't want to expose the emitter.e Array...)
obj.on = emitter.on.bind(emitter);
obj.off = emitter.off.bind(emitter);
obj.once = emitter.once.bind(emitter);
obj.emit = emitter.emit.bind(emitter);
return obj;
}

126
node_modules/mathjs/lib/esm/utils/factory.js generated vendored Normal file
View File

@@ -0,0 +1,126 @@
import { pickShallow } from './object.js';
/**
* Create a factory function, which can be used to inject dependencies.
*
* The created functions are memoized, a consecutive call of the factory
* with the exact same inputs will return the same function instance.
* The memoized cache is exposed on `factory.cache` and can be cleared
* if needed.
*
* Example:
*
* const name = 'log'
* const dependencies = ['config', 'typed', 'divideScalar', 'Complex']
*
* export const createLog = factory(name, dependencies, ({ typed, config, divideScalar, Complex }) => {
* // ... create the function log here and return it
* }
*
* @param {string} name Name of the function to be created
* @param {string[]} dependencies The names of all required dependencies
* @param {function} create Callback function called with an object with all dependencies
* @param {Object} [meta] Optional object with meta information that will be attached
* to the created factory function as property `meta`.
* @returns {function}
*/
export function factory(name, dependencies, create, meta) {
function assertAndCreate(scope) {
// we only pass the requested dependencies to the factory function
// to prevent functions to rely on dependencies that are not explicitly
// requested.
var deps = pickShallow(scope, dependencies.map(stripOptionalNotation));
assertDependencies(name, dependencies, scope);
return create(deps);
}
assertAndCreate.isFactory = true;
assertAndCreate.fn = name;
assertAndCreate.dependencies = dependencies.slice().sort();
if (meta) {
assertAndCreate.meta = meta;
}
return assertAndCreate;
}
/**
* Sort all factories such that when loading in order, the dependencies are resolved.
*
* @param {Array} factories
* @returns {Array} Returns a new array with the sorted factories.
*/
export function sortFactories(factories) {
var factoriesByName = {};
factories.forEach(factory => {
factoriesByName[factory.fn] = factory;
});
function containsDependency(factory, dependency) {
// TODO: detect circular references
if (isFactory(factory)) {
if (factory.dependencies.includes(dependency.fn || dependency.name)) {
return true;
}
if (factory.dependencies.some(d => containsDependency(factoriesByName[d], dependency))) {
return true;
}
}
return false;
}
var sorted = [];
function addFactory(factory) {
var index = 0;
while (index < sorted.length && !containsDependency(sorted[index], factory)) {
index++;
}
sorted.splice(index, 0, factory);
}
// sort regular factory functions
factories.filter(isFactory).forEach(addFactory);
// sort legacy factory functions AFTER the regular factory functions
factories.filter(factory => !isFactory(factory)).forEach(addFactory);
return sorted;
}
// TODO: comment or cleanup if unused in the end
export function create(factories) {
var scope = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
sortFactories(factories).forEach(factory => factory(scope));
return scope;
}
/**
* Test whether an object is a factory. This is the case when it has
* properties name, dependencies, and a function create.
* @param {*} obj
* @returns {boolean}
*/
export function isFactory(obj) {
return typeof obj === 'function' && typeof obj.fn === 'string' && Array.isArray(obj.dependencies);
}
/**
* Assert that all dependencies of a list with dependencies are available in the provided scope.
*
* Will throw an exception when there are dependencies missing.
*
* @param {string} name Name for the function to be created. Used to generate a useful error message
* @param {string[]} dependencies
* @param {Object} scope
*/
export function assertDependencies(name, dependencies, scope) {
var allDefined = dependencies.filter(dependency => !isOptionalDependency(dependency)) // filter optionals
.every(dependency => scope[dependency] !== undefined);
if (!allDefined) {
var missingDependencies = dependencies.filter(dependency => scope[dependency] === undefined);
// TODO: create a custom error class for this, a MathjsError or something like that
throw new Error("Cannot create function \"".concat(name, "\", ") + "some dependencies are missing: ".concat(missingDependencies.map(d => "\"".concat(d, "\"")).join(', '), "."));
}
}
export function isOptionalDependency(dependency) {
return dependency && dependency[0] === '?';
}
export function stripOptionalNotation(dependency) {
return dependency && dependency[0] === '?' ? dependency.slice(1) : dependency;
}

86
node_modules/mathjs/lib/esm/utils/function.js generated vendored Normal file
View File

@@ -0,0 +1,86 @@
// function utils
import { lruQueue } from './lruQueue.js';
/**
* Memoize a given function by caching the computed result.
* The cache of a memoized function can be cleared by deleting the `cache`
* property of the function.
*
* @param {function} fn The function to be memoized.
* Must be a pure function.
* @param {Object} [options]
* @param {function(args: Array): string} [options.hasher]
* A custom hash builder. Is JSON.stringify by default.
* @param {number | undefined} [options.limit]
* Maximum number of values that may be cached. Undefined indicates
* unlimited (default)
* @return {function} Returns the memoized function
*/
export function memoize(fn) {
var {
hasher,
limit
} = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
limit = limit == null ? Number.POSITIVE_INFINITY : limit;
hasher = hasher == null ? JSON.stringify : hasher;
return function memoize() {
if (typeof memoize.cache !== 'object') {
memoize.cache = {
values: new Map(),
lru: lruQueue(limit || Number.POSITIVE_INFINITY)
};
}
var args = [];
for (var i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
var hash = hasher(args);
if (memoize.cache.values.has(hash)) {
memoize.cache.lru.hit(hash);
return memoize.cache.values.get(hash);
}
var newVal = fn.apply(fn, args);
memoize.cache.values.set(hash, newVal);
memoize.cache.values.delete(memoize.cache.lru.hit(hash));
return newVal;
};
}
/**
* Memoize a given function by caching all results and the arguments,
* and comparing against the arguments of previous results before
* executing again.
* This is less performant than `memoize` which calculates a hash,
* which is very fast to compare. Use `memoizeCompare` only when it is
* not possible to create a unique serializable hash from the function
* arguments.
* The isEqual function must compare two sets of arguments
* and return true when equal (can be a deep equality check for example).
* @param {function} fn
* @param {function(a: *, b: *) : boolean} isEqual
* @returns {function}
*/
export function memoizeCompare(fn, isEqual) {
var memoize = function memoize() {
var args = [];
for (var i = 0; i < arguments.length; i++) {
args[i] = arguments[i];
}
for (var c = 0; c < memoize.cache.length; c++) {
var cached = memoize.cache[c];
if (isEqual(args, cached.args)) {
// TODO: move this cache entry to the top so recently used entries move up?
return cached.res;
}
}
var res = fn.apply(fn, args);
memoize.cache.unshift({
args,
res
});
return res;
};
memoize.cache = [];
return memoize;
}

195
node_modules/mathjs/lib/esm/utils/is.js generated vendored Normal file
View File

@@ -0,0 +1,195 @@
// type checks for all known types
//
// note that:
//
// - check by duck-typing on a property like `isUnit`, instead of checking instanceof.
// instanceof cannot be used because that would not allow to pass data from
// one instance of math.js to another since each has it's own instance of Unit.
// - check the `isUnit` property via the constructor, so there will be no
// matches for "fake" instances like plain objects with a property `isUnit`.
// That is important for security reasons.
// - It must not be possible to override the type checks used internally,
// for security reasons, so these functions are not exposed in the expression
// parser.
import { ObjectWrappingMap } from './map.js';
export function isNumber(x) {
return typeof x === 'number';
}
export function isBigNumber(x) {
if (!x || typeof x !== 'object' || typeof x.constructor !== 'function') {
return false;
}
if (x.isBigNumber === true && typeof x.constructor.prototype === 'object' && x.constructor.prototype.isBigNumber === true) {
return true;
}
if (typeof x.constructor.isDecimal === 'function' && x.constructor.isDecimal(x) === true) {
return true;
}
return false;
}
export function isBigInt(x) {
return typeof x === 'bigint';
}
export function isComplex(x) {
return x && typeof x === 'object' && Object.getPrototypeOf(x).isComplex === true || false;
}
export function isFraction(x) {
return x && typeof x === 'object' && Object.getPrototypeOf(x).isFraction === true || false;
}
export function isUnit(x) {
return x && x.constructor.prototype.isUnit === true || false;
}
export function isString(x) {
return typeof x === 'string';
}
export var isArray = Array.isArray;
export function isMatrix(x) {
return x && x.constructor.prototype.isMatrix === true || false;
}
/**
* Test whether a value is a collection: an Array or Matrix
* @param {*} x
* @returns {boolean} isCollection
*/
export function isCollection(x) {
return Array.isArray(x) || isMatrix(x);
}
export function isDenseMatrix(x) {
return x && x.isDenseMatrix && x.constructor.prototype.isMatrix === true || false;
}
export function isSparseMatrix(x) {
return x && x.isSparseMatrix && x.constructor.prototype.isMatrix === true || false;
}
export function isRange(x) {
return x && x.constructor.prototype.isRange === true || false;
}
export function isIndex(x) {
return x && x.constructor.prototype.isIndex === true || false;
}
export function isBoolean(x) {
return typeof x === 'boolean';
}
export function isResultSet(x) {
return x && x.constructor.prototype.isResultSet === true || false;
}
export function isHelp(x) {
return x && x.constructor.prototype.isHelp === true || false;
}
export function isFunction(x) {
return typeof x === 'function';
}
export function isDate(x) {
return x instanceof Date;
}
export function isRegExp(x) {
return x instanceof RegExp;
}
export function isObject(x) {
return !!(x && typeof x === 'object' && x.constructor === Object && !isComplex(x) && !isFraction(x));
}
/**
* Returns `true` if the passed object appears to be a Map (i.e. duck typing).
*
* Methods looked for are `get`, `set`, `keys` and `has`.
*
* @param {Map | object} object
* @returns
*/
export function isMap(object) {
// We can use the fast instanceof, or a slower duck typing check.
// The duck typing method needs to cover enough methods to not be confused with DenseMatrix.
if (!object) {
return false;
}
return object instanceof Map || object instanceof ObjectWrappingMap || typeof object.set === 'function' && typeof object.get === 'function' && typeof object.keys === 'function' && typeof object.has === 'function';
}
export function isPartitionedMap(object) {
return isMap(object) && isMap(object.a) && isMap(object.b);
}
export function isObjectWrappingMap(object) {
return isMap(object) && isObject(object.wrappedObject);
}
export function isNull(x) {
return x === null;
}
export function isUndefined(x) {
return x === undefined;
}
export function isAccessorNode(x) {
return x && x.isAccessorNode === true && x.constructor.prototype.isNode === true || false;
}
export function isArrayNode(x) {
return x && x.isArrayNode === true && x.constructor.prototype.isNode === true || false;
}
export function isAssignmentNode(x) {
return x && x.isAssignmentNode === true && x.constructor.prototype.isNode === true || false;
}
export function isBlockNode(x) {
return x && x.isBlockNode === true && x.constructor.prototype.isNode === true || false;
}
export function isConditionalNode(x) {
return x && x.isConditionalNode === true && x.constructor.prototype.isNode === true || false;
}
export function isConstantNode(x) {
return x && x.isConstantNode === true && x.constructor.prototype.isNode === true || false;
}
/* Very specialized: returns true for those nodes which in the numerator of
a fraction means that the division in that fraction has precedence over implicit
multiplication, e.g. -2/3 x parses as (-2/3) x and 3/4 x parses as (3/4) x but
6!/8 x parses as 6! / (8x). It is located here because it is shared between
parse.js and OperatorNode.js (for parsing and printing, respectively).
This should *not* be exported from mathjs, unlike most of the tests here.
Its name does not start with 'is' to prevent utils/snapshot.js from thinking
it should be exported.
*/
export function rule2Node(node) {
return isConstantNode(node) || isOperatorNode(node) && node.args.length === 1 && isConstantNode(node.args[0]) && '-+~'.includes(node.op);
}
export function isFunctionAssignmentNode(x) {
return x && x.isFunctionAssignmentNode === true && x.constructor.prototype.isNode === true || false;
}
export function isFunctionNode(x) {
return x && x.isFunctionNode === true && x.constructor.prototype.isNode === true || false;
}
export function isIndexNode(x) {
return x && x.isIndexNode === true && x.constructor.prototype.isNode === true || false;
}
export function isNode(x) {
return x && x.isNode === true && x.constructor.prototype.isNode === true || false;
}
export function isObjectNode(x) {
return x && x.isObjectNode === true && x.constructor.prototype.isNode === true || false;
}
export function isOperatorNode(x) {
return x && x.isOperatorNode === true && x.constructor.prototype.isNode === true || false;
}
export function isParenthesisNode(x) {
return x && x.isParenthesisNode === true && x.constructor.prototype.isNode === true || false;
}
export function isRangeNode(x) {
return x && x.isRangeNode === true && x.constructor.prototype.isNode === true || false;
}
export function isRelationalNode(x) {
return x && x.isRelationalNode === true && x.constructor.prototype.isNode === true || false;
}
export function isSymbolNode(x) {
return x && x.isSymbolNode === true && x.constructor.prototype.isNode === true || false;
}
export function isChain(x) {
return x && x.constructor.prototype.isChain === true || false;
}
export function typeOf(x) {
var t = typeof x;
if (t === 'object') {
if (x === null) return 'null';
if (isBigNumber(x)) return 'BigNumber'; // Special: weird mashup with Decimal
if (x.constructor && x.constructor.name) return x.constructor.name;
return 'Object'; // just in case
}
return t; // can be 'string', 'number', 'boolean', 'function', 'bigint', ...
}

487
node_modules/mathjs/lib/esm/utils/latex.js generated vendored Normal file
View File

@@ -0,0 +1,487 @@
/* eslint no-template-curly-in-string: "off" */
import escapeLatexLib from 'escape-latex';
import { hasOwnProperty } from './object.js';
export var latexSymbols = {
// GREEK LETTERS
Alpha: 'A',
alpha: '\\alpha',
Beta: 'B',
beta: '\\beta',
Gamma: '\\Gamma',
gamma: '\\gamma',
Delta: '\\Delta',
delta: '\\delta',
Epsilon: 'E',
epsilon: '\\epsilon',
varepsilon: '\\varepsilon',
Zeta: 'Z',
zeta: '\\zeta',
Eta: 'H',
eta: '\\eta',
Theta: '\\Theta',
theta: '\\theta',
vartheta: '\\vartheta',
Iota: 'I',
iota: '\\iota',
Kappa: 'K',
kappa: '\\kappa',
varkappa: '\\varkappa',
Lambda: '\\Lambda',
lambda: '\\lambda',
Mu: 'M',
mu: '\\mu',
Nu: 'N',
nu: '\\nu',
Xi: '\\Xi',
xi: '\\xi',
Omicron: 'O',
omicron: 'o',
Pi: '\\Pi',
pi: '\\pi',
varpi: '\\varpi',
Rho: 'P',
rho: '\\rho',
varrho: '\\varrho',
Sigma: '\\Sigma',
sigma: '\\sigma',
varsigma: '\\varsigma',
Tau: 'T',
tau: '\\tau',
Upsilon: '\\Upsilon',
upsilon: '\\upsilon',
Phi: '\\Phi',
phi: '\\phi',
varphi: '\\varphi',
Chi: 'X',
chi: '\\chi',
Psi: '\\Psi',
psi: '\\psi',
Omega: '\\Omega',
omega: '\\omega',
// logic
true: '\\mathrm{True}',
false: '\\mathrm{False}',
// other
i: 'i',
// TODO use \i ??
inf: '\\infty',
Inf: '\\infty',
infinity: '\\infty',
Infinity: '\\infty',
oo: '\\infty',
lim: '\\lim',
undefined: '\\mathbf{?}'
};
export var latexOperators = {
transpose: '^\\top',
ctranspose: '^H',
factorial: '!',
pow: '^',
dotPow: '.^\\wedge',
// TODO find ideal solution
unaryPlus: '+',
unaryMinus: '-',
bitNot: '\\~',
// TODO find ideal solution
not: '\\neg',
multiply: '\\cdot',
divide: '\\frac',
// TODO how to handle that properly?
dotMultiply: '.\\cdot',
// TODO find ideal solution
dotDivide: '.:',
// TODO find ideal solution
mod: '\\mod',
add: '+',
subtract: '-',
to: '\\rightarrow',
leftShift: '<<',
rightArithShift: '>>',
rightLogShift: '>>>',
equal: '=',
unequal: '\\neq',
smaller: '<',
larger: '>',
smallerEq: '\\leq',
largerEq: '\\geq',
bitAnd: '\\&',
bitXor: '\\underline{|}',
bitOr: '|',
and: '\\wedge',
xor: '\\veebar',
or: '\\vee'
};
export var latexFunctions = {
// arithmetic
abs: {
1: '\\left|${args[0]}\\right|'
},
add: {
2: "\\left(${args[0]}".concat(latexOperators.add, "${args[1]}\\right)")
},
cbrt: {
1: '\\sqrt[3]{${args[0]}}'
},
ceil: {
1: '\\left\\lceil${args[0]}\\right\\rceil'
},
cube: {
1: '\\left(${args[0]}\\right)^3'
},
divide: {
2: '\\frac{${args[0]}}{${args[1]}}'
},
dotDivide: {
2: "\\left(${args[0]}".concat(latexOperators.dotDivide, "${args[1]}\\right)")
},
dotMultiply: {
2: "\\left(${args[0]}".concat(latexOperators.dotMultiply, "${args[1]}\\right)")
},
dotPow: {
2: "\\left(${args[0]}".concat(latexOperators.dotPow, "${args[1]}\\right)")
},
exp: {
1: '\\exp\\left(${args[0]}\\right)'
},
expm1: "\\left(e".concat(latexOperators.pow, "{${args[0]}}-1\\right)"),
fix: {
1: '\\mathrm{${name}}\\left(${args[0]}\\right)'
},
floor: {
1: '\\left\\lfloor${args[0]}\\right\\rfloor'
},
gcd: '\\gcd\\left(${args}\\right)',
hypot: '\\hypot\\left(${args}\\right)',
log: {
1: '\\ln\\left(${args[0]}\\right)',
2: '\\log_{${args[1]}}\\left(${args[0]}\\right)'
},
log10: {
1: '\\log_{10}\\left(${args[0]}\\right)'
},
log1p: {
1: '\\ln\\left(${args[0]}+1\\right)',
2: '\\log_{${args[1]}}\\left(${args[0]}+1\\right)'
},
log2: '\\log_{2}\\left(${args[0]}\\right)',
mod: {
2: "\\left(${args[0]}".concat(latexOperators.mod, "${args[1]}\\right)")
},
multiply: {
2: "\\left(${args[0]}".concat(latexOperators.multiply, "${args[1]}\\right)")
},
norm: {
1: '\\left\\|${args[0]}\\right\\|',
2: undefined // use default template
},
nthRoot: {
2: '\\sqrt[${args[1]}]{${args[0]}}'
},
nthRoots: {
2: '\\{y : $y^{args[1]} = {${args[0]}}\\}'
},
pow: {
2: "\\left(${args[0]}\\right)".concat(latexOperators.pow, "{${args[1]}}")
},
round: {
1: '\\left\\lfloor${args[0]}\\right\\rceil',
2: undefined // use default template
},
sign: {
1: '\\mathrm{${name}}\\left(${args[0]}\\right)'
},
sqrt: {
1: '\\sqrt{${args[0]}}'
},
square: {
1: '\\left(${args[0]}\\right)^2'
},
subtract: {
2: "\\left(${args[0]}".concat(latexOperators.subtract, "${args[1]}\\right)")
},
unaryMinus: {
1: "".concat(latexOperators.unaryMinus, "\\left(${args[0]}\\right)")
},
unaryPlus: {
1: "".concat(latexOperators.unaryPlus, "\\left(${args[0]}\\right)")
},
// bitwise
bitAnd: {
2: "\\left(${args[0]}".concat(latexOperators.bitAnd, "${args[1]}\\right)")
},
bitNot: {
1: latexOperators.bitNot + '\\left(${args[0]}\\right)'
},
bitOr: {
2: "\\left(${args[0]}".concat(latexOperators.bitOr, "${args[1]}\\right)")
},
bitXor: {
2: "\\left(${args[0]}".concat(latexOperators.bitXor, "${args[1]}\\right)")
},
leftShift: {
2: "\\left(${args[0]}".concat(latexOperators.leftShift, "${args[1]}\\right)")
},
rightArithShift: {
2: "\\left(${args[0]}".concat(latexOperators.rightArithShift, "${args[1]}\\right)")
},
rightLogShift: {
2: "\\left(${args[0]}".concat(latexOperators.rightLogShift, "${args[1]}\\right)")
},
// combinatorics
bellNumbers: {
1: '\\mathrm{B}_{${args[0]}}'
},
catalan: {
1: '\\mathrm{C}_{${args[0]}}'
},
stirlingS2: {
2: '\\mathrm{S}\\left(${args}\\right)'
},
// complex
arg: {
1: '\\arg\\left(${args[0]}\\right)'
},
conj: {
1: '\\left(${args[0]}\\right)^*'
},
im: {
1: '\\Im\\left\\lbrace${args[0]}\\right\\rbrace'
},
re: {
1: '\\Re\\left\\lbrace${args[0]}\\right\\rbrace'
},
// logical
and: {
2: "\\left(${args[0]}".concat(latexOperators.and, "${args[1]}\\right)")
},
not: {
1: latexOperators.not + '\\left(${args[0]}\\right)'
},
or: {
2: "\\left(${args[0]}".concat(latexOperators.or, "${args[1]}\\right)")
},
xor: {
2: "\\left(${args[0]}".concat(latexOperators.xor, "${args[1]}\\right)")
},
// matrix
cross: {
2: '\\left(${args[0]}\\right)\\times\\left(${args[1]}\\right)'
},
ctranspose: {
1: "\\left(${args[0]}\\right)".concat(latexOperators.ctranspose)
},
det: {
1: '\\det\\left(${args[0]}\\right)'
},
dot: {
2: '\\left(${args[0]}\\cdot${args[1]}\\right)'
},
expm: {
1: '\\exp\\left(${args[0]}\\right)'
},
inv: {
1: '\\left(${args[0]}\\right)^{-1}'
},
pinv: {
1: '\\left(${args[0]}\\right)^{+}'
},
sqrtm: {
1: "{${args[0]}}".concat(latexOperators.pow, "{\\frac{1}{2}}")
},
trace: {
1: '\\mathrm{tr}\\left(${args[0]}\\right)'
},
transpose: {
1: "\\left(${args[0]}\\right)".concat(latexOperators.transpose)
},
// probability
combinations: {
2: '\\binom{${args[0]}}{${args[1]}}'
},
combinationsWithRep: {
2: '\\left(\\!\\!{\\binom{${args[0]}}{${args[1]}}}\\!\\!\\right)'
},
factorial: {
1: "\\left(${args[0]}\\right)".concat(latexOperators.factorial)
},
gamma: {
1: '\\Gamma\\left(${args[0]}\\right)'
},
lgamma: {
1: '\\ln\\Gamma\\left(${args[0]}\\right)'
},
// relational
equal: {
2: "\\left(${args[0]}".concat(latexOperators.equal, "${args[1]}\\right)")
},
larger: {
2: "\\left(${args[0]}".concat(latexOperators.larger, "${args[1]}\\right)")
},
largerEq: {
2: "\\left(${args[0]}".concat(latexOperators.largerEq, "${args[1]}\\right)")
},
smaller: {
2: "\\left(${args[0]}".concat(latexOperators.smaller, "${args[1]}\\right)")
},
smallerEq: {
2: "\\left(${args[0]}".concat(latexOperators.smallerEq, "${args[1]}\\right)")
},
unequal: {
2: "\\left(${args[0]}".concat(latexOperators.unequal, "${args[1]}\\right)")
},
// special
erf: {
1: 'erf\\left(${args[0]}\\right)'
},
// statistics
max: '\\max\\left(${args}\\right)',
min: '\\min\\left(${args}\\right)',
variance: '\\mathrm{Var}\\left(${args}\\right)',
// trigonometry
acos: {
1: '\\cos^{-1}\\left(${args[0]}\\right)'
},
acosh: {
1: '\\cosh^{-1}\\left(${args[0]}\\right)'
},
acot: {
1: '\\cot^{-1}\\left(${args[0]}\\right)'
},
acoth: {
1: '\\coth^{-1}\\left(${args[0]}\\right)'
},
acsc: {
1: '\\csc^{-1}\\left(${args[0]}\\right)'
},
acsch: {
1: '\\mathrm{csch}^{-1}\\left(${args[0]}\\right)'
},
asec: {
1: '\\sec^{-1}\\left(${args[0]}\\right)'
},
asech: {
1: '\\mathrm{sech}^{-1}\\left(${args[0]}\\right)'
},
asin: {
1: '\\sin^{-1}\\left(${args[0]}\\right)'
},
asinh: {
1: '\\sinh^{-1}\\left(${args[0]}\\right)'
},
atan: {
1: '\\tan^{-1}\\left(${args[0]}\\right)'
},
atan2: {
2: '\\mathrm{atan2}\\left(${args}\\right)'
},
atanh: {
1: '\\tanh^{-1}\\left(${args[0]}\\right)'
},
cos: {
1: '\\cos\\left(${args[0]}\\right)'
},
cosh: {
1: '\\cosh\\left(${args[0]}\\right)'
},
cot: {
1: '\\cot\\left(${args[0]}\\right)'
},
coth: {
1: '\\coth\\left(${args[0]}\\right)'
},
csc: {
1: '\\csc\\left(${args[0]}\\right)'
},
csch: {
1: '\\mathrm{csch}\\left(${args[0]}\\right)'
},
sec: {
1: '\\sec\\left(${args[0]}\\right)'
},
sech: {
1: '\\mathrm{sech}\\left(${args[0]}\\right)'
},
sin: {
1: '\\sin\\left(${args[0]}\\right)'
},
sinh: {
1: '\\sinh\\left(${args[0]}\\right)'
},
tan: {
1: '\\tan\\left(${args[0]}\\right)'
},
tanh: {
1: '\\tanh\\left(${args[0]}\\right)'
},
// unit
to: {
2: "\\left(${args[0]}".concat(latexOperators.to, "${args[1]}\\right)")
},
// utils
numeric: function numeric(node, options) {
// Not sure if this is strictly right but should work correctly for the vast majority of use cases.
return node.args[0].toTex();
},
// type
number: {
0: '0',
1: '\\left(${args[0]}\\right)',
2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)'
},
string: {
0: '\\mathtt{""}',
1: '\\mathrm{string}\\left(${args[0]}\\right)'
},
bignumber: {
0: '0',
1: '\\left(${args[0]}\\right)'
},
bigint: {
0: '0',
1: '\\left(${args[0]}\\right)'
},
complex: {
0: '0',
1: '\\left(${args[0]}\\right)',
2: "\\left(\\left(${args[0]}\\right)+".concat(latexSymbols.i, "\\cdot\\left(${args[1]}\\right)\\right)")
},
matrix: {
0: '\\begin{bmatrix}\\end{bmatrix}',
1: '\\left(${args[0]}\\right)',
2: '\\left(${args[0]}\\right)'
},
sparse: {
0: '\\begin{bsparse}\\end{bsparse}',
1: '\\left(${args[0]}\\right)'
},
unit: {
1: '\\left(${args[0]}\\right)',
2: '\\left(\\left(${args[0]}\\right)${args[1]}\\right)'
}
};
export var defaultTemplate = '\\mathrm{${name}}\\left(${args}\\right)';
var latexUnits = {
deg: '^\\circ'
};
export function escapeLatex(string) {
return escapeLatexLib(string, {
preserveFormatting: true
});
}
// @param {string} name
// @param {boolean} isUnit
export function toSymbol(name, isUnit) {
isUnit = typeof isUnit === 'undefined' ? false : isUnit;
if (isUnit) {
if (hasOwnProperty(latexUnits, name)) {
return latexUnits[name];
}
return '\\mathrm{' + escapeLatex(name) + '}';
}
if (hasOwnProperty(latexSymbols, name)) {
return latexSymbols[name];
}
return escapeLatex(name);
}

16
node_modules/mathjs/lib/esm/utils/log.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
/**
* Log a console.warn message only once
*/
export var warnOnce = (() => {
var messages = {};
return function warnOnce() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var message = args.join(', ');
if (!messages[message]) {
messages[message] = true;
console.warn('Warning:', ...args);
}
};
})();

51
node_modules/mathjs/lib/esm/utils/lruQueue.js generated vendored Normal file
View File

@@ -0,0 +1,51 @@
// (c) 2018, Mariusz Nowak
// SPDX-License-Identifier: ISC
// Derived from https://github.com/medikoo/lru-queue
export function lruQueue(limit) {
var size = 0;
var base = 1;
var queue = Object.create(null);
var map = Object.create(null);
var index = 0;
var del = function del(id) {
var oldIndex = map[id];
if (!oldIndex) return;
delete queue[oldIndex];
delete map[id];
--size;
if (base !== oldIndex) return;
if (!size) {
index = 0;
base = 1;
return;
}
while (!Object.prototype.hasOwnProperty.call(queue, ++base)) {/* empty */}
};
limit = Math.abs(limit);
return {
hit: function hit(id) {
var oldIndex = map[id];
var nuIndex = ++index;
queue[nuIndex] = id;
map[id] = nuIndex;
if (!oldIndex) {
++size;
if (size <= limit) return undefined;
id = queue[base];
del(id);
return id;
}
delete queue[oldIndex];
if (base !== oldIndex) return undefined;
while (!Object.prototype.hasOwnProperty.call(queue, ++base)) {/* empty */}
return undefined;
},
delete: del,
clear: function clear() {
size = index = 0;
base = 1;
queue = Object.create(null);
map = Object.create(null);
}
};
}

203
node_modules/mathjs/lib/esm/utils/map.js generated vendored Normal file
View File

@@ -0,0 +1,203 @@
import { getSafeProperty, isSafeProperty, setSafeProperty } from './customs.js';
import { isMap, isObject } from './is.js';
/**
* A map facade on a bare object.
*
* The small number of methods needed to implement a scope,
* forwarding on to the SafeProperty functions. Over time, the codebase
* will stop using this method, as all objects will be Maps, rather than
* more security prone objects.
*/
export class ObjectWrappingMap {
constructor(object) {
this.wrappedObject = object;
this[Symbol.iterator] = this.entries;
}
keys() {
return Object.keys(this.wrappedObject).filter(key => this.has(key)).values();
}
get(key) {
return getSafeProperty(this.wrappedObject, key);
}
set(key, value) {
setSafeProperty(this.wrappedObject, key, value);
return this;
}
has(key) {
return isSafeProperty(this.wrappedObject, key) && key in this.wrappedObject;
}
entries() {
return mapIterator(this.keys(), key => [key, this.get(key)]);
}
forEach(callback) {
for (var key of this.keys()) {
callback(this.get(key), key, this);
}
}
delete(key) {
if (isSafeProperty(this.wrappedObject, key)) {
delete this.wrappedObject[key];
}
}
clear() {
for (var key of this.keys()) {
this.delete(key);
}
}
get size() {
return Object.keys(this.wrappedObject).length;
}
}
/**
* Create a map with two partitions: a and b.
* The set with bKeys determines which keys/values are read/written to map b,
* all other values are read/written to map a
*
* For example:
*
* const a = new Map()
* const b = new Map()
* const p = new PartitionedMap(a, b, new Set(['x', 'y']))
*
* In this case, values `x` and `y` are read/written to map `b`,
* all other values are read/written to map `a`.
*/
export class PartitionedMap {
/**
* @param {Map} a
* @param {Map} b
* @param {Set} bKeys
*/
constructor(a, b, bKeys) {
this.a = a;
this.b = b;
this.bKeys = bKeys;
this[Symbol.iterator] = this.entries;
}
get(key) {
return this.bKeys.has(key) ? this.b.get(key) : this.a.get(key);
}
set(key, value) {
if (this.bKeys.has(key)) {
this.b.set(key, value);
} else {
this.a.set(key, value);
}
return this;
}
has(key) {
return this.b.has(key) || this.a.has(key);
}
keys() {
return new Set([...this.a.keys(), ...this.b.keys()])[Symbol.iterator]();
}
entries() {
return mapIterator(this.keys(), key => [key, this.get(key)]);
}
forEach(callback) {
for (var key of this.keys()) {
callback(this.get(key), key, this);
}
}
delete(key) {
return this.bKeys.has(key) ? this.b.delete(key) : this.a.delete(key);
}
clear() {
this.a.clear();
this.b.clear();
}
get size() {
return [...this.keys()].length;
}
}
/**
* Create a new iterator that maps over the provided iterator, applying a mapping function to each item
*/
function mapIterator(it, callback) {
return {
next: () => {
var n = it.next();
return n.done ? n : {
value: callback(n.value),
done: false
};
}
};
}
/**
* Creates an empty map, or whatever your platform's polyfill is.
*
* @returns an empty Map or Map like object.
*/
export function createEmptyMap() {
return new Map();
}
/**
* Creates a Map from the given object.
*
* @param { Map | { [key: string]: unknown } | undefined } mapOrObject
* @returns
*/
export function createMap(mapOrObject) {
if (!mapOrObject) {
return createEmptyMap();
}
if (isMap(mapOrObject)) {
return mapOrObject;
}
if (isObject(mapOrObject)) {
return new ObjectWrappingMap(mapOrObject);
}
throw new Error('createMap can create maps from objects or Maps');
}
/**
* Unwraps a map into an object.
*
* @param {Map} map
* @returns { [key: string]: unknown }
*/
export function toObject(map) {
if (map instanceof ObjectWrappingMap) {
return map.wrappedObject;
}
var object = {};
for (var key of map.keys()) {
var value = map.get(key);
setSafeProperty(object, key, value);
}
return object;
}
/**
* Copies the contents of key-value pairs from each `objects` in to `map`.
*
* Object is `objects` can be a `Map` or object.
*
* This is the `Map` analog to `Object.assign`.
*/
export function assign(map) {
for (var _len = arguments.length, objects = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
objects[_key - 1] = arguments[_key];
}
for (var args of objects) {
if (!args) {
continue;
}
if (isMap(args)) {
for (var key of args.keys()) {
map.set(key, args.get(key));
}
} else if (isObject(args)) {
for (var _key2 of Object.keys(args)) {
map.set(_key2, args[_key2]);
}
}
}
return map;
}

15
node_modules/mathjs/lib/esm/utils/noop.js generated vendored Normal file
View File

@@ -0,0 +1,15 @@
export function noBignumber() {
throw new Error('No "bignumber" implementation available');
}
export function noFraction() {
throw new Error('No "fraction" implementation available');
}
export function noMatrix() {
throw new Error('No "matrix" implementation available');
}
export function noIndex() {
throw new Error('No "index" implementation available');
}
export function noSubset() {
throw new Error('No "matrix" implementation available');
}

737
node_modules/mathjs/lib/esm/utils/number.js generated vendored Normal file
View File

@@ -0,0 +1,737 @@
import { isBigNumber, isNumber, isObject } from './is.js';
/**
* @typedef {{sign: '+' | '-' | '', coefficients: number[], exponent: number}} SplitValue
*/
/**
* Check if a number is integer
* @param {number | boolean} value
* @return {boolean} isInteger
*/
export function isInteger(value) {
if (typeof value === 'boolean') {
return true;
}
return isFinite(value) ? value === Math.round(value) : false;
}
/**
* Check if a string contains an integer
* @param {string} str
* @return {boolean} isInteger
*/
export function isIntegerStr(str) {
// regex matching strings like "123" and "-123"
return /^-?\d+$/.test(str);
}
/**
* Ensure the number type is compatible with the provided value.
* If not, return 'number' instead.
*
* For example:
*
* safeNumberType('2.3', { number: 'bigint', numberFallback: 'number' })
*
* will return 'number' and not 'bigint' because trying to create a bigint with
* value 2.3 would throw an exception.
*
* @param {string} numberStr
* @param {{
* number: 'number' | 'BigNumber' | 'bigint' | 'Fraction'
* numberFallback: 'number' | 'BigNumber'
* }} config
* @returns {'number' | 'BigNumber' | 'bigint' | 'Fraction'}
*/
export function safeNumberType(numberStr, config) {
if (config.number === 'bigint' && !isIntegerStr(numberStr)) {
return config.numberFallback;
}
return config.number;
}
/**
* Calculate the sign of a number
* @param {number} x
* @returns {number}
*/
export var sign = Math.sign || function (x) {
if (x > 0) {
return 1;
} else if (x < 0) {
return -1;
} else {
return 0;
}
};
/**
* Calculate the base-2 logarithm of a number
* @param {number} x
* @returns {number}
*/
export var log2 = Math.log2 || function log2(x) {
return Math.log(x) / Math.LN2;
};
/**
* Calculate the base-10 logarithm of a number
* @param {number} x
* @returns {number}
*/
export var log10 = Math.log10 || function log10(x) {
return Math.log(x) / Math.LN10;
};
/**
* Calculate the natural logarithm of a number + 1
* @param {number} x
* @returns {number}
*/
export var log1p = Math.log1p || function (x) {
return Math.log(x + 1);
};
/**
* Calculate cubic root for a number
*
* Code from es6-shim.js:
* https://github.com/paulmillr/es6-shim/blob/master/es6-shim.js#L1564-L1577
*
* @param {number} x
* @returns {number} Returns the cubic root of x
*/
export var cbrt = Math.cbrt || function cbrt(x) {
if (x === 0) {
return x;
}
var negate = x < 0;
var result;
if (negate) {
x = -x;
}
if (isFinite(x)) {
result = Math.exp(Math.log(x) / 3);
// from https://en.wikipedia.org/wiki/Cube_root#Numerical_methods
result = (x / (result * result) + 2 * result) / 3;
} else {
result = x;
}
return negate ? -result : result;
};
/**
* Calculates exponentiation minus 1
* @param {number} x
* @return {number} res
*/
export var expm1 = Math.expm1 || function expm1(x) {
return x >= 2e-4 || x <= -2e-4 ? Math.exp(x) - 1 : x + x * x / 2 + x * x * x / 6;
};
/**
* Formats a number in a given base
* @param {number} n
* @param {number} base
* @param {number} size
* @returns {string}
*/
function formatNumberToBase(n, base, size) {
var prefixes = {
2: '0b',
8: '0o',
16: '0x'
};
var prefix = prefixes[base];
var suffix = '';
if (size) {
if (size < 1) {
throw new Error('size must be in greater than 0');
}
if (!isInteger(size)) {
throw new Error('size must be an integer');
}
if (n > 2 ** (size - 1) - 1 || n < -(2 ** (size - 1))) {
throw new Error("Value must be in range [-2^".concat(size - 1, ", 2^").concat(size - 1, "-1]"));
}
if (!isInteger(n)) {
throw new Error('Value must be an integer');
}
if (n < 0) {
n = n + 2 ** size;
}
suffix = "i".concat(size);
}
var sign = '';
if (n < 0) {
n = -n;
sign = '-';
}
return "".concat(sign).concat(prefix).concat(n.toString(base)).concat(suffix);
}
/**
* Convert a number to a formatted string representation.
*
* Syntax:
*
* format(value)
* format(value, options)
* format(value, precision)
* format(value, fn)
*
* Where:
*
* {number} value The value to be formatted
* {Object} options An object with formatting options. Available options:
* {string} notation
* Number notation. Choose from:
* 'fixed' Always use regular number notation.
* For example '123.40' and '14000000'
* 'exponential' Always use exponential notation.
* For example '1.234e+2' and '1.4e+7'
* 'engineering' Always use engineering notation.
* For example '123.4e+0' and '14.0e+6'
* 'auto' (default) Regular number notation for numbers
* having an absolute value between
* `lowerExp` and `upperExp` bounds, and
* uses exponential notation elsewhere.
* Lower bound is included, upper bound
* is excluded.
* For example '123.4' and '1.4e7'.
* 'bin', 'oct, or
* 'hex' Format the number using binary, octal,
* or hexadecimal notation.
* For example '0b1101' and '0x10fe'.
* {number} wordSize The word size in bits to use for formatting
* in binary, octal, or hexadecimal notation.
* To be used only with 'bin', 'oct', or 'hex'
* values for 'notation' option. When this option
* is defined the value is formatted as a signed
* twos complement integer of the given word size
* and the size suffix is appended to the output.
* For example
* format(-1, {notation: 'hex', wordSize: 8}) === '0xffi8'.
* Default value is undefined.
* {number} precision A number between 0 and 16 to round
* the digits of the number.
* In case of notations 'exponential',
* 'engineering', and 'auto',
* `precision` defines the total
* number of significant digits returned.
* In case of notation 'fixed',
* `precision` defines the number of
* significant digits after the decimal
* point.
* `precision` is undefined by default,
* not rounding any digits.
* {number} lowerExp Exponent determining the lower boundary
* for formatting a value with an exponent
* when `notation='auto`.
* Default value is `-3`.
* {number} upperExp Exponent determining the upper boundary
* for formatting a value with an exponent
* when `notation='auto`.
* Default value is `5`.
* {Function} fn A custom formatting function. Can be used to override the
* built-in notations. Function `fn` is called with `value` as
* parameter and must return a string. Is useful for example to
* format all values inside a matrix in a particular way.
*
* Examples:
*
* format(6.4) // '6.4'
* format(1240000) // '1.24e6'
* format(1/3) // '0.3333333333333333'
* format(1/3, 3) // '0.333'
* format(21385, 2) // '21000'
* format(12.071, {notation: 'fixed'}) // '12'
* format(2.3, {notation: 'fixed', precision: 2}) // '2.30'
* format(52.8, {notation: 'exponential'}) // '5.28e+1'
* format(12345678, {notation: 'engineering'}) // '12.345678e+6'
*
* @param {number} value
* @param {Object | Function | number} [options]
* @return {string} str The formatted value
*/
export function format(value, options) {
if (typeof options === 'function') {
// handle format(value, fn)
return options(value);
}
// handle special cases
if (value === Infinity) {
return 'Infinity';
} else if (value === -Infinity) {
return '-Infinity';
} else if (isNaN(value)) {
return 'NaN';
}
var {
notation,
precision,
wordSize
} = normalizeFormatOptions(options);
// handle the various notations
switch (notation) {
case 'fixed':
return toFixed(value, precision);
case 'exponential':
return toExponential(value, precision);
case 'engineering':
return toEngineering(value, precision);
case 'bin':
return formatNumberToBase(value, 2, wordSize);
case 'oct':
return formatNumberToBase(value, 8, wordSize);
case 'hex':
return formatNumberToBase(value, 16, wordSize);
case 'auto':
// remove trailing zeros after the decimal point
return toPrecision(value, precision, options).replace(/((\.\d*?)(0+))($|e)/, function () {
var digits = arguments[2];
var e = arguments[4];
return digits !== '.' ? digits + e : e;
});
default:
throw new Error('Unknown notation "' + notation + '". ' + 'Choose "auto", "exponential", "fixed", "bin", "oct", or "hex.');
}
}
/**
* Normalize format options into an object:
* {
* notation: string,
* precision: number | undefined,
* wordSize: number | undefined
* }
*/
export function normalizeFormatOptions(options) {
// default values for options
var notation = 'auto';
var precision;
var wordSize;
if (options !== undefined) {
if (isNumber(options)) {
precision = options;
} else if (isBigNumber(options)) {
precision = options.toNumber();
} else if (isObject(options)) {
if (options.precision !== undefined) {
precision = _toNumberOrThrow(options.precision, () => {
throw new Error('Option "precision" must be a number or BigNumber');
});
}
if (options.wordSize !== undefined) {
wordSize = _toNumberOrThrow(options.wordSize, () => {
throw new Error('Option "wordSize" must be a number or BigNumber');
});
}
if (options.notation) {
notation = options.notation;
}
} else {
throw new Error('Unsupported type of options, number, BigNumber, or object expected');
}
}
return {
notation,
precision,
wordSize
};
}
/**
* Split a number into sign, coefficients, and exponent
* @param {number | string} value
* @return {SplitValue}
* Returns an object containing sign, coefficients, and exponent
*/
export function splitNumber(value) {
// parse the input value
var match = String(value).toLowerCase().match(/^(-?)(\d+\.?\d*)(e([+-]?\d+))?$/);
if (!match) {
throw new SyntaxError('Invalid number ' + value);
}
var sign = match[1];
var digits = match[2];
var exponent = parseFloat(match[4] || '0');
var dot = digits.indexOf('.');
exponent += dot !== -1 ? dot - 1 : digits.length - 1;
var coefficients = digits.replace('.', '') // remove the dot (must be removed before removing leading zeros)
.replace(/^0*/, function (zeros) {
// remove leading zeros, add their count to the exponent
exponent -= zeros.length;
return '';
}).replace(/0*$/, '') // remove trailing zeros
.split('').map(function (d) {
return parseInt(d);
});
if (coefficients.length === 0) {
coefficients.push(0);
exponent++;
}
return {
sign,
coefficients,
exponent
};
}
/**
* Format a number in engineering notation. Like '1.23e+6', '2.3e+0', '3.500e-3'
* @param {number | string} value
* @param {number} [precision] Optional number of significant figures to return.
*/
export function toEngineering(value, precision) {
if (isNaN(value) || !isFinite(value)) {
return String(value);
}
var split = splitNumber(value);
var rounded = roundDigits(split, precision);
var e = rounded.exponent;
var c = rounded.coefficients;
// find nearest lower multiple of 3 for exponent
var newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3;
if (isNumber(precision)) {
// add zeroes to give correct sig figs
while (precision > c.length || e - newExp + 1 > c.length) {
c.push(0);
}
} else {
// concatenate coefficients with necessary zeros
// add zeros if necessary (for example: 1e+8 -> 100e+6)
var missingZeros = Math.abs(e - newExp) - (c.length - 1);
for (var i = 0; i < missingZeros; i++) {
c.push(0);
}
}
// find difference in exponents
var expDiff = Math.abs(e - newExp);
var decimalIdx = 1;
// push decimal index over by expDiff times
while (expDiff > 0) {
decimalIdx++;
expDiff--;
}
// if all coefficient values are zero after the decimal point and precision is unset, don't add a decimal value.
// otherwise concat with the rest of the coefficients
var decimals = c.slice(decimalIdx).join('');
var decimalVal = isNumber(precision) && decimals.length || decimals.match(/[1-9]/) ? '.' + decimals : '';
var str = c.slice(0, decimalIdx).join('') + decimalVal + 'e' + (e >= 0 ? '+' : '') + newExp.toString();
return rounded.sign + str;
}
/**
* Format a number with fixed notation.
* @param {number | string} value
* @param {number} [precision=undefined] Optional number of decimals after the
* decimal point. null by default.
*/
export function toFixed(value, precision) {
if (isNaN(value) || !isFinite(value)) {
return String(value);
}
var splitValue = splitNumber(value);
var rounded = typeof precision === 'number' ? roundDigits(splitValue, splitValue.exponent + 1 + precision) : splitValue;
var c = rounded.coefficients;
var p = rounded.exponent + 1; // exponent may have changed
// append zeros if needed
var pp = p + (precision || 0);
if (c.length < pp) {
c = c.concat(zeros(pp - c.length));
}
// prepend zeros if needed
if (p < 0) {
c = zeros(-p + 1).concat(c);
p = 1;
}
// insert a dot if needed
if (p < c.length) {
c.splice(p, 0, p === 0 ? '0.' : '.');
}
return rounded.sign + c.join('');
}
/**
* Format a number in exponential notation. Like '1.23e+5', '2.3e+0', '3.500e-3'
* @param {number | string} value
* @param {number} [precision] Number of digits in formatted output.
* If not provided, the maximum available digits
* is used.
*/
export function toExponential(value, precision) {
if (isNaN(value) || !isFinite(value)) {
return String(value);
}
// round if needed, else create a clone
var split = splitNumber(value);
var rounded = precision ? roundDigits(split, precision) : split;
var c = rounded.coefficients;
var e = rounded.exponent;
// append zeros if needed
if (c.length < precision) {
c = c.concat(zeros(precision - c.length));
}
// format as `C.CCCe+EEE` or `C.CCCe-EEE`
var first = c.shift();
return rounded.sign + first + (c.length > 0 ? '.' + c.join('') : '') + 'e' + (e >= 0 ? '+' : '') + e;
}
/**
* Format a number with a certain precision
* @param {number | string} value
* @param {number} [precision=undefined] Optional number of digits.
* @param {{lowerExp: number | undefined, upperExp: number | undefined}} [options]
* By default:
* lowerExp = -3 (incl)
* upper = +5 (excl)
* @return {string}
*/
export function toPrecision(value, precision, options) {
if (isNaN(value) || !isFinite(value)) {
return String(value);
}
// determine lower and upper bound for exponential notation.
var lowerExp = _toNumberOrDefault(options === null || options === void 0 ? void 0 : options.lowerExp, -3);
var upperExp = _toNumberOrDefault(options === null || options === void 0 ? void 0 : options.upperExp, 5);
var split = splitNumber(value);
var rounded = precision ? roundDigits(split, precision) : split;
if (rounded.exponent < lowerExp || rounded.exponent >= upperExp) {
// exponential notation
return toExponential(value, precision);
} else {
var c = rounded.coefficients;
var e = rounded.exponent;
// append trailing zeros
if (c.length < precision) {
c = c.concat(zeros(precision - c.length));
}
// append trailing zeros
// TODO: simplify the next statement
c = c.concat(zeros(e - c.length + 1 + (c.length < precision ? precision - c.length : 0)));
// prepend zeros
c = zeros(-e).concat(c);
var dot = e > 0 ? e : 0;
if (dot < c.length - 1) {
c.splice(dot + 1, 0, '.');
}
return rounded.sign + c.join('');
}
}
/**
* Round the number of digits of a number *
* @param {SplitValue} split A value split with .splitNumber(value)
* @param {number} precision A positive integer
* @return {SplitValue}
* Returns an object containing sign, coefficients, and exponent
* with rounded digits
*/
export function roundDigits(split, precision) {
// create a clone
var rounded = {
sign: split.sign,
coefficients: split.coefficients,
exponent: split.exponent
};
var c = rounded.coefficients;
// prepend zeros if needed
while (precision <= 0) {
c.unshift(0);
rounded.exponent++;
precision++;
}
if (c.length > precision) {
var removed = c.splice(precision, c.length - precision);
if (removed[0] >= 5) {
var i = precision - 1;
c[i]++;
while (c[i] === 10) {
c.pop();
if (i === 0) {
c.unshift(0);
rounded.exponent++;
i++;
}
i--;
c[i]++;
}
}
}
return rounded;
}
/**
* Create an array filled with zeros.
* @param {number} length
* @return {Array}
*/
function zeros(length) {
var arr = [];
for (var i = 0; i < length; i++) {
arr.push(0);
}
return arr;
}
/**
* Count the number of significant digits of a number.
*
* For example:
* 2.34 returns 3
* 0.0034 returns 2
* 120.5e+30 returns 4
*
* @param {number} value
* @return {number} digits Number of significant digits
*/
export function digits(value) {
return value.toExponential().replace(/e.*$/, '') // remove exponential notation
.replace(/^0\.?0*|\./, '') // remove decimal point and leading zeros
.length;
}
/**
* Minimum number added to one that makes the result different than one
*/
export var DBL_EPSILON = Number.EPSILON || 2.2204460492503130808472633361816E-16;
/**
* Compares two floating point numbers.
* @param {number} a - First value to compare
* @param {number} b - Second value to compare
* @param {number} [relTol=1e-09] - The relative tolerance, indicating the maximum allowed difference relative to the larger absolute value. Must be greater than 0.
* @param {number} [absTol=1e-12] - The minimum absolute tolerance, useful for comparisons near zero. Must be at least 0.
* @return {boolean} whether the two numbers are nearly equal
*
* @throws {Error} If `relTol` is less than or equal to 0.
* @throws {Error} If `absTol` is less than 0.
*
* @example
* nearlyEqual(1.000000001, 1.0, 1e-8); // true
* nearlyEqual(1.000000002, 1.0, 0); // false
* nearlyEqual(1.0, 1.009, undefined, 0.01); // true
* nearlyEqual(0.000000001, 0.0, undefined, 1e-8); // true
*/
export function nearlyEqual(a, b) {
var relTol = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1e-8;
var absTol = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
if (relTol <= 0) {
throw new Error('Relative tolerance must be greater than 0');
}
if (absTol < 0) {
throw new Error('Absolute tolerance must be at least 0');
}
// NaN
if (isNaN(a) || isNaN(b)) {
return false;
}
if (!isFinite(a) || !isFinite(b)) {
return a === b;
}
if (a === b) {
return true;
}
// abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
return Math.abs(a - b) <= Math.max(relTol * Math.max(Math.abs(a), Math.abs(b)), absTol);
}
/**
* Calculate the hyperbolic arccos of a number
* @param {number} x
* @return {number}
*/
export var acosh = Math.acosh || function (x) {
return Math.log(Math.sqrt(x * x - 1) + x);
};
export var asinh = Math.asinh || function (x) {
return Math.log(Math.sqrt(x * x + 1) + x);
};
/**
* Calculate the hyperbolic arctangent of a number
* @param {number} x
* @return {number}
*/
export var atanh = Math.atanh || function (x) {
return Math.log((1 + x) / (1 - x)) / 2;
};
/**
* Calculate the hyperbolic cosine of a number
* @param {number} x
* @returns {number}
*/
export var cosh = Math.cosh || function (x) {
return (Math.exp(x) + Math.exp(-x)) / 2;
};
/**
* Calculate the hyperbolic sine of a number
* @param {number} x
* @returns {number}
*/
export var sinh = Math.sinh || function (x) {
return (Math.exp(x) - Math.exp(-x)) / 2;
};
/**
* Calculate the hyperbolic tangent of a number
* @param {number} x
* @returns {number}
*/
export var tanh = Math.tanh || function (x) {
var e = Math.exp(2 * x);
return (e - 1) / (e + 1);
};
/**
* Returns a value with the magnitude of x and the sign of y.
* @param {number} x
* @param {number} y
* @returns {number}
*/
export function copysign(x, y) {
var signx = x > 0 ? true : x < 0 ? false : 1 / x === Infinity;
var signy = y > 0 ? true : y < 0 ? false : 1 / y === Infinity;
return signx ^ signy ? -x : x;
}
function _toNumberOrThrow(value, onError) {
if (isNumber(value)) {
return value;
} else if (isBigNumber(value)) {
return value.toNumber();
} else {
onError();
}
}
function _toNumberOrDefault(value, defaultValue) {
if (isNumber(value)) {
return value;
} else if (isBigNumber(value)) {
return value.toNumber();
} else {
return defaultValue;
}
}

376
node_modules/mathjs/lib/esm/utils/object.js generated vendored Normal file
View File

@@ -0,0 +1,376 @@
import { isBigNumber, isObject } from './is.js';
/**
* Clone an object
*
* clone(x)
*
* Can clone any primitive type, array, and object.
* If x has a function clone, this function will be invoked to clone the object.
*
* @param {*} x
* @return {*} clone
*/
export function clone(x) {
var type = typeof x;
// immutable primitive types
if (type === 'number' || type === 'bigint' || type === 'string' || type === 'boolean' || x === null || x === undefined) {
return x;
}
// use clone function of the object when available
if (typeof x.clone === 'function') {
return x.clone();
}
// array
if (Array.isArray(x)) {
return x.map(function (value) {
return clone(value);
});
}
if (x instanceof Date) return new Date(x.valueOf());
if (isBigNumber(x)) return x; // bignumbers are immutable
// object
if (isObject(x)) {
return mapObject(x, clone);
}
if (type === 'function') {
// we assume that the function is immutable
return x;
}
throw new TypeError("Cannot clone: unknown type of value (value: ".concat(x, ")"));
}
/**
* Apply map to all properties of an object
* @param {Object} object
* @param {function} callback
* @return {Object} Returns a copy of the object with mapped properties
*/
export function mapObject(object, callback) {
var clone = {};
for (var key in object) {
if (hasOwnProperty(object, key)) {
clone[key] = callback(object[key]);
}
}
return clone;
}
/**
* Extend object a with the properties of object b
* @param {Object} a
* @param {Object} b
* @return {Object} a
*/
export function extend(a, b) {
for (var prop in b) {
if (hasOwnProperty(b, prop)) {
a[prop] = b[prop];
}
}
return a;
}
/**
* Deep extend an object a with the properties of object b
* @param {Object} a
* @param {Object} b
* @returns {Object}
*/
export function deepExtend(a, b) {
// TODO: add support for Arrays to deepExtend
if (Array.isArray(b)) {
throw new TypeError('Arrays are not supported by deepExtend');
}
for (var prop in b) {
// We check against prop not being in Object.prototype or Function.prototype
// to prevent polluting for example Object.__proto__.
if (hasOwnProperty(b, prop) && !(prop in Object.prototype) && !(prop in Function.prototype)) {
if (b[prop] && b[prop].constructor === Object) {
if (a[prop] === undefined) {
a[prop] = {};
}
if (a[prop] && a[prop].constructor === Object) {
deepExtend(a[prop], b[prop]);
} else {
a[prop] = b[prop];
}
} else if (Array.isArray(b[prop])) {
throw new TypeError('Arrays are not supported by deepExtend');
} else {
a[prop] = b[prop];
}
}
}
return a;
}
/**
* Deep test equality of all fields in two pairs of arrays or objects.
* Compares values and functions strictly (ie. 2 is not the same as '2').
* @param {Array | Object} a
* @param {Array | Object} b
* @returns {boolean}
*/
export function deepStrictEqual(a, b) {
var prop, i, len;
if (Array.isArray(a)) {
if (!Array.isArray(b)) {
return false;
}
if (a.length !== b.length) {
return false;
}
for (i = 0, len = a.length; i < len; i++) {
if (!deepStrictEqual(a[i], b[i])) {
return false;
}
}
return true;
} else if (typeof a === 'function') {
return a === b;
} else if (a instanceof Object) {
if (Array.isArray(b) || !(b instanceof Object)) {
return false;
}
for (prop in a) {
// noinspection JSUnfilteredForInLoop
if (!(prop in b) || !deepStrictEqual(a[prop], b[prop])) {
return false;
}
}
for (prop in b) {
// noinspection JSUnfilteredForInLoop
if (!(prop in a)) {
return false;
}
}
return true;
} else {
return a === b;
}
}
/**
* Recursively flatten a nested object.
* @param {Object} nestedObject
* @return {Object} Returns the flattened object
*/
export function deepFlatten(nestedObject) {
var flattenedObject = {};
_deepFlatten(nestedObject, flattenedObject);
return flattenedObject;
}
// helper function used by deepFlatten
function _deepFlatten(nestedObject, flattenedObject) {
for (var prop in nestedObject) {
if (hasOwnProperty(nestedObject, prop)) {
var value = nestedObject[prop];
if (typeof value === 'object' && value !== null) {
_deepFlatten(value, flattenedObject);
} else {
flattenedObject[prop] = value;
}
}
}
}
/**
* Test whether the current JavaScript engine supports Object.defineProperty
* @returns {boolean} returns true if supported
*/
export function canDefineProperty() {
// test needed for broken IE8 implementation
try {
if (Object.defineProperty) {
Object.defineProperty({}, 'x', {
get: function get() {
return null;
}
});
return true;
}
} catch (e) {}
return false;
}
/**
* Attach a lazy loading property to a constant.
* The given function `fn` is called once when the property is first requested.
*
* @param {Object} object Object where to add the property
* @param {string} prop Property name
* @param {Function} valueResolver Function returning the property value. Called
* without arguments.
*/
export function lazy(object, prop, valueResolver) {
var _uninitialized = true;
var _value;
Object.defineProperty(object, prop, {
get: function get() {
if (_uninitialized) {
_value = valueResolver();
_uninitialized = false;
}
return _value;
},
set: function set(value) {
_value = value;
_uninitialized = false;
},
configurable: true,
enumerable: true
});
}
/**
* Traverse a path into an object.
* When a namespace is missing, it will be created
* @param {Object} object
* @param {string | string[]} path A dot separated string like 'name.space'
* @return {Object} Returns the object at the end of the path
*/
export function traverse(object, path) {
if (path && typeof path === 'string') {
return traverse(object, path.split('.'));
}
var obj = object;
if (path) {
for (var i = 0; i < path.length; i++) {
var key = path[i];
if (!(key in obj)) {
obj[key] = {};
}
obj = obj[key];
}
}
return obj;
}
/**
* A safe hasOwnProperty
* @param {Object} object
* @param {string} property
*/
export function hasOwnProperty(object, property) {
return object && Object.hasOwnProperty.call(object, property);
}
/**
* Test whether an object is a factory. a factory has fields:
*
* - factory: function (type: Object, config: Object, load: function, typed: function [, math: Object]) (required)
* - name: string (optional)
* - path: string A dot separated path (optional)
* - math: boolean If true (false by default), the math namespace is passed
* as fifth argument of the factory function
*
* @param {*} object
* @returns {boolean}
*/
export function isLegacyFactory(object) {
return object && typeof object.factory === 'function';
}
/**
* Get a nested property from an object
* @param {Object} object
* @param {string | string[]} path
* @returns {Object}
*/
export function get(object, path) {
if (typeof path === 'string') {
if (isPath(path)) {
return get(object, path.split('.'));
} else {
return object[path];
}
}
var child = object;
for (var i = 0; i < path.length; i++) {
var key = path[i];
child = child ? child[key] : undefined;
}
return child;
}
/**
* Set a nested property in an object
* Mutates the object itself
* If the path doesn't exist, it will be created
* @param {Object} object
* @param {string | string[]} path
* @param {*} value
* @returns {Object}
*/
export function set(object, path, value) {
if (typeof path === 'string') {
if (isPath(path)) {
return set(object, path.split('.'), value);
} else {
object[path] = value;
return object;
}
}
var child = object;
for (var i = 0; i < path.length - 1; i++) {
var key = path[i];
if (child[key] === undefined) {
child[key] = {};
}
child = child[key];
}
if (path.length > 0) {
var lastKey = path[path.length - 1];
child[lastKey] = value;
}
return object;
}
/**
* Create an object composed of the picked object properties
* @param {Object} object
* @param {string[]} properties
* @param {function} [transform] Optional value to transform a value when picking it
* @return {Object}
*/
export function pick(object, properties, transform) {
var copy = {};
for (var i = 0; i < properties.length; i++) {
var key = properties[i];
var value = get(object, key);
if (value !== undefined) {
set(copy, key, transform ? transform(value, key) : value);
}
}
return copy;
}
/**
* Shallow version of pick, creating an object composed of the picked object properties
* but not for nested properties
* @param {Object} object
* @param {string[]} properties
* @return {Object}
*/
export function pickShallow(object, properties) {
var copy = {};
for (var i = 0; i < properties.length; i++) {
var key = properties[i];
var value = object[key];
if (value !== undefined) {
copy[key] = value;
}
}
return copy;
}
// helper function to test whether a string contains a path like 'user.name'
function isPath(str) {
return str.includes('.');
}

88
node_modules/mathjs/lib/esm/utils/optimizeCallback.js generated vendored Normal file
View File

@@ -0,0 +1,88 @@
import typed from 'typed-function';
import { get, arraySize } from './array.js';
import { typeOf as _typeOf } from './is.js';
/**
* Simplifies a callback function by reducing its complexity and potentially improving its performance.
*
* @param {Function} callback The original callback function to simplify.
* @param {Array|Matrix} array The array that will be used with the callback function.
* @param {string} name The name of the function that is using the callback.
* @returns {Function} Returns a simplified version of the callback function.
*/
export function optimizeCallback(callback, array, name) {
if (typed.isTypedFunction(callback)) {
var firstIndex = (array.isMatrix ? array.size() : arraySize(array)).map(() => 0);
var firstValue = array.isMatrix ? array.get(firstIndex) : get(array, firstIndex);
var hasSingleSignature = Object.keys(callback.signatures).length === 1;
var numberOfArguments = _findNumberOfArguments(callback, firstValue, firstIndex, array);
var fastCallback = hasSingleSignature ? Object.values(callback.signatures)[0] : callback;
if (numberOfArguments >= 1 && numberOfArguments <= 3) {
return function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _tryFunctionWithArgs(fastCallback, args.slice(0, numberOfArguments), name, callback.name);
};
}
return function () {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _tryFunctionWithArgs(fastCallback, args, name, callback.name);
};
}
return callback;
}
function _findNumberOfArguments(callback, value, index, array) {
var testArgs = [value, index, array];
for (var i = 3; i > 0; i--) {
var args = testArgs.slice(0, i);
if (typed.resolve(callback, args) !== null) {
return i;
}
}
}
/**
* @param {function} func The selected function taken from one of the signatures of the callback function
* @param {Array} args List with arguments to apply to the selected signature
* @param {string} mappingFnName the name of the function that is using the callback
* @param {string} callbackName the name of the callback function
* @returns {*} Returns the return value of the invoked signature
* @throws {TypeError} Throws an error when no matching signature was found
*/
function _tryFunctionWithArgs(func, args, mappingFnName, callbackName) {
try {
return func(...args);
} catch (err) {
_createCallbackError(err, args, mappingFnName, callbackName);
}
}
/**
* Creates and throws a detailed TypeError when a callback function fails.
*
* @param {Error} err The original error thrown by the callback function.
* @param {Array} args The arguments that were passed to the callback function.
* @param {string} mappingFnName The name of the function that is using the callback.
* @param {string} callbackName The name of the callback function.
* @throws {TypeError} Throws a detailed TypeError with enriched error message.
*/
function _createCallbackError(err, args, mappingFnName, callbackName) {
var _err$data;
// Enrich the error message so the user understands that it took place inside the callback function
if (err instanceof TypeError && ((_err$data = err.data) === null || _err$data === void 0 ? void 0 : _err$data.category) === 'wrongType') {
var argsDesc = [];
argsDesc.push("value: ".concat(_typeOf(args[0])));
if (args.length >= 2) {
argsDesc.push("index: ".concat(_typeOf(args[1])));
}
if (args.length >= 3) {
argsDesc.push("array: ".concat(_typeOf(args[2])));
}
throw new TypeError("Function ".concat(mappingFnName, " cannot apply callback arguments ") + "".concat(callbackName, "(").concat(argsDesc.join(', '), ") at index ").concat(JSON.stringify(args[1])));
} else {
throw new TypeError("Function ".concat(mappingFnName, " cannot apply callback arguments ") + "to function ".concat(callbackName, ": ").concat(err.message));
}
}

1
node_modules/mathjs/lib/esm/utils/print.js generated vendored Normal file
View File

@@ -0,0 +1 @@
export var printTemplate = /\$([\w.]+)/g;

14
node_modules/mathjs/lib/esm/utils/product.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
/** @param {number} i
* @param {number} n
* @returns {number} product of i to n
*/
export function product(i, n) {
if (n < i) {
return 1;
}
if (n === i) {
return n;
}
var half = n + i >> 1; // divide (n + i) by 2 and truncate to integer
return product(i, half) * product(half + 1, n);
}

18
node_modules/mathjs/lib/esm/utils/scope.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
import { ObjectWrappingMap, PartitionedMap } from './map.js';
/**
* Create a new scope which can access the parent scope,
* but does not affect it when written. This is suitable for variable definitions
* within a block node, or function definition.
*
* If parent scope has a createSubScope method, it delegates to that. Otherwise,
* creates an empty map, and copies the parent scope to it, adding in
* the remaining `args`.
*
* @param {Map} parentScope
* @param {Object} args
* @returns {PartitionedMap}
*/
export function createSubScope(parentScope, args) {
return new PartitionedMap(parentScope, new ObjectWrappingMap(args), new Set(Object.keys(args)));
}

227
node_modules/mathjs/lib/esm/utils/snapshot.js generated vendored Normal file
View File

@@ -0,0 +1,227 @@
import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
/**
* This file contains helper methods to create expected snapshot structures
* of both instance and ES6 exports.
*
* The files are located here and not under /test or /tools so it's transpiled
* into ES5 code under /lib and can be used straight by node.js
*/
import assert from 'assert';
import * as allIsFunctions from './is.js';
import { create } from '../core/create.js';
import { endsWith } from './string.js';
export var validateTypeOf = allIsFunctions.typeOf;
export function validateBundle(expectedBundleStructure, bundle) {
var originalWarn = console.warn;
console.warn = function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (args.join(' ').includes('is moved to') && args.join(' ').includes('Please use the new location instead')) {
// Ignore warnings like:
// Warning: math.type.isNumber is moved to math.isNumber in v6.0.0. Please use the new location instead.
return;
}
originalWarn.apply(console, args);
};
try {
var issues = [];
// see whether all expected functions and objects are there
traverse(expectedBundleStructure, (expectedType, path) => {
var actualValue = get(bundle, path);
var actualType = validateTypeOf(actualValue);
var message = actualType === 'undefined' ? 'Missing entry in bundle. ' + "Path: ".concat(JSON.stringify(path), ", expected type: ").concat(expectedType, ", actual type: ").concat(actualType) : 'Unexpected entry type in bundle. ' + "Path: ".concat(JSON.stringify(path), ", expected type: ").concat(expectedType, ", actual type: ").concat(actualType);
if (actualType !== expectedType) {
issues.push({
actualType,
expectedType,
message
});
console.warn(message);
}
});
// see whether there are any functions or objects that shouldn't be there
traverse(bundle, (actualValue, path) => {
var actualType = validateTypeOf(actualValue);
var expectedType = get(expectedBundleStructure, path) || 'undefined';
// FIXME: ugly to have these special cases
if (path.join('.').includes('docs.')) {
// ignore the contents of docs
return;
}
if (path.join('.').includes('all.')) {
// ignore the contents of all dependencies
return;
}
var message = expectedType === 'undefined' ? 'Unknown entry in bundle. ' + 'Is there a new function added which is missing in this snapshot test? ' + "Path: ".concat(JSON.stringify(path), ", expected type: ").concat(expectedType, ", actual type: ").concat(actualType) : 'Unexpected entry type in bundle. ' + "Path: ".concat(JSON.stringify(path), ", expected type: ").concat(expectedType, ", actual type: ").concat(actualType);
if (actualType !== expectedType) {
issues.push({
actualType,
expectedType,
message
});
console.warn(message);
}
});
// assert on the first issue (if any)
if (issues.length > 0) {
var {
actualType,
expectedType,
message
} = issues[0];
console.warn("".concat(issues.length, " bundle issues found"));
assert.strictEqual(actualType, expectedType, message);
}
} finally {
console.warn = originalWarn;
}
}
/**
* Based on an object with factory functions, create the expected
* structures for ES6 export and a mathjs instance.
* @param {Object} factories
* @return {{expectedInstanceStructure: Object, expectedES6Structure: Object}}
*/
export function createSnapshotFromFactories(factories) {
var math = create(factories);
var allFactoryFunctions = {};
var allFunctionsConstantsClasses = {};
var allFunctionsConstants = {};
var allTransformFunctions = {};
var allDependencyCollections = {};
var allClasses = {};
var allNodeClasses = {};
Object.keys(factories).forEach(factoryName => {
var factory = factories[factoryName];
var name = factory.fn;
var isTransformFunction = factory.meta && factory.meta.isTransformFunction;
var isClass = !isLowerCase(name[0]) && validateTypeOf(math[name]) === 'function';
var dependenciesName = factory.fn + (isTransformFunction ? 'Transform' : '') + 'Dependencies';
allFactoryFunctions[factoryName] = 'function';
allFunctionsConstantsClasses[name] = validateTypeOf(math[name]);
allDependencyCollections[dependenciesName] = 'Object';
if (isTransformFunction) {
allTransformFunctions[name] = 'function';
}
if (isClass) {
if (endsWith(name, 'Node')) {
allNodeClasses[name] = 'function';
} else {
allClasses[name] = 'function';
}
} else {
allFunctionsConstants[name] = validateTypeOf(math[name]);
}
});
var embeddedDocs = {};
Object.keys(factories).forEach(factoryName => {
var factory = factories[factoryName];
var name = factory.fn;
if (isLowerCase(factory.fn[0])) {
// ignore class names starting with upper case
embeddedDocs[name] = 'Object';
}
});
embeddedDocs = exclude(embeddedDocs, ['equalScalar', 'apply', 'addScalar', 'subtractScalar', 'multiplyScalar', 'print', 'divideScalar', 'parse', 'compile', 'parser', 'chain', 'reviver', 'replacer']);
var allTypeChecks = {};
Object.keys(allIsFunctions).forEach(name => {
if (name.indexOf('is') === 0) {
allTypeChecks[name] = 'function';
}
});
var allErrorClasses = {
ArgumentsError: 'function',
DimensionError: 'function',
IndexError: 'function'
};
var expectedInstanceStructure = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, allFunctionsConstantsClasses), {}, {
on: 'function',
off: 'function',
once: 'function',
emit: 'function',
import: 'function',
config: 'function',
create: 'function',
factory: 'function'
}, allTypeChecks), allErrorClasses), {}, {
expression: {
transform: _objectSpread({}, allTransformFunctions),
mathWithTransform: _objectSpread(_objectSpread({}, exclude(allFunctionsConstants, ['chain'])), {}, {
config: 'function'
})
}
});
var expectedES6Structure = _objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({}, exclude(allFunctionsConstantsClasses, ['E', 'false', 'Infinity', 'NaN', 'null', 'PI', 'true'])), {}, {
create: 'function',
config: 'function',
factory: 'function',
_true: 'boolean',
_false: 'boolean',
_null: 'null',
_Infinity: 'number',
_NaN: 'number'
}, allTypeChecks), allErrorClasses), allDependencyCollections), allFactoryFunctions), {}, {
docs: embeddedDocs
});
return {
expectedInstanceStructure,
expectedES6Structure
};
}
function traverse(obj) {
var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (value, path) => {};
var path = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
// FIXME: ugly to have these special cases
if (path.length > 0 && path[0].includes('Dependencies')) {
// special case for objects holding a collection of dependencies
callback(obj, path);
} else if (validateTypeOf(obj) === 'Array') {
obj.map((item, index) => traverse(item, callback, path.concat(index)));
} else if (validateTypeOf(obj) === 'Object') {
Object.keys(obj).forEach(key => {
// FIXME: ugly to have these special cases
// ignore special case of deprecated docs
if (key === 'docs' && path.join('.') === 'expression') {
return;
}
traverse(obj[key], callback, path.concat(key));
});
} else {
callback(obj, path);
}
}
function get(object, path) {
var child = object;
for (var i = 0; i < path.length; i++) {
var key = path[i];
child = child ? child[key] : undefined;
}
return child;
}
/**
* Create a copy of the provided `object` and delete
* all properties listed in `excludedProperties`
* @param {Object} object
* @param {string[]} excludedProperties
* @return {Object}
*/
function exclude(object, excludedProperties) {
var strippedObject = _extends({}, object);
excludedProperties.forEach(excludedProperty => {
delete strippedObject[excludedProperty];
});
return strippedObject;
}
function isLowerCase(text) {
return typeof text === 'string' && text.toLowerCase() === text;
}

194
node_modules/mathjs/lib/esm/utils/string.js generated vendored Normal file
View File

@@ -0,0 +1,194 @@
import { isBigNumber, isString, typeOf } from './is.js';
import { format as formatNumber } from './number.js';
import { format as formatBigNumber } from './bignumber/formatter.js';
/**
* Check if a text ends with a certain string.
* @param {string} text
* @param {string} search
*/
export function endsWith(text, search) {
var start = text.length - search.length;
var end = text.length;
return text.substring(start, end) === search;
}
/**
* Format a value of any type into a string.
*
* Usage:
* math.format(value)
* math.format(value, precision)
* math.format(value, options)
*
* When value is a function:
*
* - When the function has a property `syntax`, it returns this
* syntax description.
* - In other cases, a string `'function'` is returned.
*
* When `value` is an Object:
*
* - When the object contains a property `format` being a function, this
* function is invoked as `value.format(options)` and the result is returned.
* - When the object has its own `toString` method, this method is invoked
* and the result is returned.
* - In other cases the function will loop over all object properties and
* return JSON object notation like '{"a": 2, "b": 3}'.
*
* Example usage:
* math.format(2/7) // '0.2857142857142857'
* math.format(math.pi, 3) // '3.14'
* math.format(new Complex(2, 3)) // '2 + 3i'
* math.format('hello') // '"hello"'
*
* @param {*} value Value to be stringified
* @param {Object | number | Function} [options]
* Formatting options. See src/utils/number.js:format for a
* description of the available options controlling number output.
* This generic "format" also supports the option property `truncate: NN`
* giving the maximum number NN of characters to return (if there would
* have been more, they are deleted and replaced by an ellipsis).
* @return {string} str
*/
export function format(value, options) {
var result = _format(value, options);
if (options && typeof options === 'object' && 'truncate' in options && result.length > options.truncate) {
return result.substring(0, options.truncate - 3) + '...';
}
return result;
}
function _format(value, options) {
if (typeof value === 'number') {
return formatNumber(value, options);
}
if (isBigNumber(value)) {
return formatBigNumber(value, options);
}
// note: we use unsafe duck-typing here to check for Fractions, this is
// ok here since we're only invoking toString or concatenating its values
if (looksLikeFraction(value)) {
if (!options || options.fraction !== 'decimal') {
// output as ratio, like '1/3'
return value.s * value.n + '/' + value.d;
} else {
// output as decimal, like '0.(3)'
return value.toString();
}
}
if (Array.isArray(value)) {
return formatArray(value, options);
}
if (isString(value)) {
return stringify(value);
}
if (typeof value === 'function') {
return value.syntax ? String(value.syntax) : 'function';
}
if (value && typeof value === 'object') {
if (typeof value.format === 'function') {
return value.format(options);
} else if (value && value.toString(options) !== {}.toString()) {
// this object has a non-native toString method, use that one
return value.toString(options);
} else {
var entries = Object.keys(value).map(key => {
return stringify(key) + ': ' + format(value[key], options);
});
return '{' + entries.join(', ') + '}';
}
}
return String(value);
}
/**
* Stringify a value into a string enclosed in double quotes.
* Unescaped double quotes and backslashes inside the value are escaped.
* @param {*} value
* @return {string}
*/
export function stringify(value) {
var text = String(value);
var escaped = '';
var i = 0;
while (i < text.length) {
var c = text.charAt(i);
escaped += c in controlCharacters ? controlCharacters[c] : c;
i++;
}
return '"' + escaped + '"';
}
var controlCharacters = {
'"': '\\"',
'\\': '\\\\',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t'
};
/**
* Escape special HTML characters
* @param {*} value
* @return {string}
*/
export function escape(value) {
var text = String(value);
text = text.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
return text;
}
/**
* Recursively format an n-dimensional matrix
* Example output: "[[1, 2], [3, 4]]"
* @param {Array} array
* @param {Object | number | Function} [options] Formatting options. See
* lib/utils/number:format for a
* description of the available
* options.
* @returns {string} str
*/
function formatArray(array, options) {
if (Array.isArray(array)) {
var str = '[';
var len = array.length;
for (var i = 0; i < len; i++) {
if (i !== 0) {
str += ', ';
}
str += formatArray(array[i], options);
}
str += ']';
return str;
} else {
return format(array, options);
}
}
/**
* Check whether a value looks like a Fraction (unsafe duck-type check)
* @param {*} value
* @return {boolean}
*/
function looksLikeFraction(value) {
return value && typeof value === 'object' && typeof value.s === 'number' && typeof value.n === 'number' && typeof value.d === 'number' || false;
}
/**
* Compare two strings
* @param {string} x
* @param {string} y
* @returns {number}
*/
export function compareText(x, y) {
// we don't want to convert numbers to string, only accept string input
if (!isString(x)) {
throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + typeOf(x) + ', index: 0)');
}
if (!isString(y)) {
throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + typeOf(y) + ', index: 1)');
}
return x === y ? 0 : x > y ? 1 : -1;
}

20
node_modules/mathjs/lib/esm/utils/switch.js generated vendored Normal file
View File

@@ -0,0 +1,20 @@
/**
* Transpose a matrix
* @param {Array} mat
* @returns {Array} ret
* @private
*/
export function _switch(mat) {
var I = mat.length;
var J = mat[0].length;
var i, j;
var ret = [];
for (j = 0; j < J; j++) {
var tmp = [];
for (i = 0; i < I; i++) {
tmp.push(mat[i][j]);
}
ret.push(tmp);
}
return ret;
}