feat:node-modules
This commit is contained in:
872
node_modules/mathjs/lib/cjs/utils/array.js
generated
vendored
Normal file
872
node_modules/mathjs/lib/cjs/utils/array.js
generated
vendored
Normal file
@@ -0,0 +1,872 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.arraySize = arraySize;
|
||||
exports.broadcastArrays = broadcastArrays;
|
||||
exports.broadcastSizes = broadcastSizes;
|
||||
exports.broadcastTo = broadcastTo;
|
||||
exports.checkBroadcastingRules = checkBroadcastingRules;
|
||||
exports.clone = clone;
|
||||
exports.concat = concat;
|
||||
exports.filter = filter;
|
||||
exports.filterRegExp = filterRegExp;
|
||||
exports.flatten = flatten;
|
||||
exports.forEach = forEach;
|
||||
exports.generalize = generalize;
|
||||
exports.get = get;
|
||||
exports.getArrayDataType = getArrayDataType;
|
||||
exports.identify = identify;
|
||||
exports.initial = initial;
|
||||
exports.isEmptyIndex = isEmptyIndex;
|
||||
exports.join = join;
|
||||
exports.last = last;
|
||||
exports.map = map;
|
||||
exports.processSizesWildcard = processSizesWildcard;
|
||||
exports.recurse = recurse;
|
||||
exports.reshape = reshape;
|
||||
exports.resize = resize;
|
||||
exports.squeeze = squeeze;
|
||||
exports.stretch = stretch;
|
||||
exports.unsqueeze = unsqueeze;
|
||||
exports.validate = validate;
|
||||
exports.validateIndex = validateIndex;
|
||||
exports.validateIndexSourceSize = validateIndexSourceSize;
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
var _number = require("./number.js");
|
||||
var _is = require("./is.js");
|
||||
var _string = require("./string.js");
|
||||
var _DimensionError = require("../error/DimensionError.js");
|
||||
var _IndexError = require("../error/IndexError.js");
|
||||
var _object = require("./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
|
||||
*/
|
||||
function arraySize(x) {
|
||||
const 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) {
|
||||
let i;
|
||||
const len = array.length;
|
||||
if (len !== size[dim]) {
|
||||
throw new _DimensionError.DimensionError(len, size[dim]);
|
||||
}
|
||||
if (dim < size.length - 1) {
|
||||
// recursively validate each child array
|
||||
const dimNext = dim + 1;
|
||||
for (i = 0; i < len; i++) {
|
||||
const child = array[i];
|
||||
if (!Array.isArray(child)) {
|
||||
throw new _DimensionError.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.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
|
||||
*/
|
||||
function validate(array, size) {
|
||||
const isScalar = size.length === 0;
|
||||
if (isScalar) {
|
||||
// scalar
|
||||
if (Array.isArray(array)) {
|
||||
throw new _DimensionError.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
|
||||
*/
|
||||
function validateIndexSourceSize(value, index) {
|
||||
const valueSize = value.isMatrix ? value._size : arraySize(value);
|
||||
const 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.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
|
||||
*/
|
||||
function validateIndex(index, length) {
|
||||
if (index !== undefined) {
|
||||
if (!(0, _is.isNumber)(index) || !(0, _number.isInteger)(index)) {
|
||||
throw new TypeError('Index must be an integer (value: ' + index + ')');
|
||||
}
|
||||
if (index < 0 || typeof length === 'number' && index >= length) {
|
||||
throw new _IndexError.IndexError(index, length);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if and index has empty values
|
||||
* @param {number} index Zero-based index
|
||||
*/
|
||||
function isEmptyIndex(index) {
|
||||
for (let i = 0; i < index._dimensions.length; ++i) {
|
||||
const dimension = index._dimensions[i];
|
||||
if (dimension._data && (0, _is.isArray)(dimension._data)) {
|
||||
if (dimension._size[0] === 0) {
|
||||
return true;
|
||||
}
|
||||
} else if (dimension.isRange) {
|
||||
if (dimension.start === dimension.end) {
|
||||
return true;
|
||||
}
|
||||
} else if ((0, _is.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
|
||||
*/
|
||||
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 (!(0, _is.isNumber)(value) || !(0, _number.isInteger)(value) || value < 0) {
|
||||
throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + (0, _string.format)(size) + ')');
|
||||
}
|
||||
});
|
||||
|
||||
// convert number to an array
|
||||
if ((0, _is.isNumber)(array) || (0, _is.isBigNumber)(array)) {
|
||||
array = [array];
|
||||
}
|
||||
|
||||
// recursively resize the array
|
||||
const _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) {
|
||||
let i;
|
||||
let elem;
|
||||
const oldLen = array.length;
|
||||
const newLen = size[dim];
|
||||
const minLen = Math.min(oldLen, newLen);
|
||||
|
||||
// apply new length
|
||||
array.length = newLen;
|
||||
if (dim < size.length - 1) {
|
||||
// non-last dimension
|
||||
const 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
|
||||
*/
|
||||
function reshape(array, sizes) {
|
||||
const flatArray = flatten(array);
|
||||
const currentLength = flatArray.length;
|
||||
if (!Array.isArray(array) || !Array.isArray(sizes)) {
|
||||
throw new TypeError('Array expected');
|
||||
}
|
||||
if (sizes.length === 0) {
|
||||
throw new _DimensionError.DimensionError(0, currentLength, '!=');
|
||||
}
|
||||
sizes = processSizesWildcard(sizes, currentLength);
|
||||
const newLength = product(sizes);
|
||||
if (currentLength !== newLength) {
|
||||
throw new _DimensionError.DimensionError(newLength, currentLength, '!=');
|
||||
}
|
||||
try {
|
||||
return _reshape(flatArray, sizes);
|
||||
} catch (e) {
|
||||
if (e instanceof _DimensionError.DimensionError) {
|
||||
throw new _DimensionError.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.
|
||||
*/
|
||||
function processSizesWildcard(sizes, currentLength) {
|
||||
const newLength = product(sizes);
|
||||
const processedSizes = sizes.slice();
|
||||
const WILDCARD = -1;
|
||||
const wildCardIndex = sizes.indexOf(WILDCARD);
|
||||
const isMoreThanOneWildcard = sizes.indexOf(WILDCARD, wildCardIndex + 1) >= 0;
|
||||
if (isMoreThanOneWildcard) {
|
||||
throw new Error('More than one wildcard in sizes');
|
||||
}
|
||||
const hasWildcard = wildCardIndex >= 0;
|
||||
const 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
|
||||
let tmpArray = array;
|
||||
let tmpArray2;
|
||||
// for each dimensions starting by the last one and ignoring the first one
|
||||
for (let sizeIndex = sizes.length - 1; sizeIndex > 0; sizeIndex--) {
|
||||
const size = sizes[sizeIndex];
|
||||
tmpArray2 = [];
|
||||
|
||||
// aggregate the elements of the current tmpArray in elements of the requested size
|
||||
const length = tmpArray.length / size;
|
||||
for (let 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
|
||||
*/
|
||||
function squeeze(array, size) {
|
||||
const 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
|
||||
let 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) {
|
||||
let i, ii;
|
||||
if (dim < dims) {
|
||||
const 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
|
||||
*/
|
||||
function unsqueeze(array, dims, outer, size) {
|
||||
const s = size || arraySize(array);
|
||||
|
||||
// unsqueeze outer dimensions
|
||||
if (outer) {
|
||||
for (let 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) {
|
||||
let i, ii;
|
||||
if (Array.isArray(array)) {
|
||||
const next = dim + 1;
|
||||
for (i = 0, ii = array.length; i < ii; i++) {
|
||||
array[i] = _unsqueeze(array[i], dims, next);
|
||||
}
|
||||
} else {
|
||||
for (let 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)
|
||||
*/
|
||||
function flatten(array) {
|
||||
if (!Array.isArray(array)) {
|
||||
// if not an array, return as is
|
||||
return array;
|
||||
}
|
||||
const 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
|
||||
*/
|
||||
function map(array, callback) {
|
||||
return Array.prototype.map.call(array, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* A safe forEach
|
||||
* @param {Array} array
|
||||
* @param {function} callback
|
||||
*/
|
||||
function forEach(array, callback) {
|
||||
Array.prototype.forEach.call(array, callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* A safe filter
|
||||
* @param {Array} array
|
||||
* @param {function} callback
|
||||
*/
|
||||
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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
function identify(a) {
|
||||
if (!Array.isArray(a)) {
|
||||
throw new TypeError('Array input expected');
|
||||
}
|
||||
if (a.length === 0) {
|
||||
return a;
|
||||
}
|
||||
const b = [];
|
||||
let count = 0;
|
||||
b[0] = {
|
||||
value: a[0],
|
||||
identifier: 0
|
||||
};
|
||||
for (let 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
|
||||
*/
|
||||
function generalize(a) {
|
||||
if (!Array.isArray(a)) {
|
||||
throw new TypeError('Array input expected');
|
||||
}
|
||||
if (a.length === 0) {
|
||||
return a;
|
||||
}
|
||||
const b = [];
|
||||
for (let 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}
|
||||
*/
|
||||
function getArrayDataType(array, typeOf) {
|
||||
let type; // to hold type info
|
||||
let length = 0; // to hold length value to ensure it has consistent sizes
|
||||
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
const item = array[i];
|
||||
const 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;
|
||||
}
|
||||
const 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 {*}
|
||||
*/
|
||||
function last(array) {
|
||||
return array[array.length - 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all but the last element of array.
|
||||
* @param {array}
|
||||
* @returns {*}
|
||||
*/
|
||||
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.DimensionError(a.length, b.length);
|
||||
}
|
||||
const c = [];
|
||||
for (let 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
|
||||
*/
|
||||
function concat() {
|
||||
const arrays = Array.prototype.slice.call(arguments, 0, -1);
|
||||
const 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
|
||||
*/
|
||||
function broadcastSizes() {
|
||||
for (var _len = arguments.length, sizes = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
sizes[_key] = arguments[_key];
|
||||
}
|
||||
const dimensions = sizes.map(s => s.length);
|
||||
const N = Math.max(...dimensions);
|
||||
const sizeMax = new Array(N).fill(null);
|
||||
// check for every size
|
||||
for (let i = 0; i < sizes.length; i++) {
|
||||
const size = sizes[i];
|
||||
const dim = dimensions[i];
|
||||
for (let j = 0; j < dim; j++) {
|
||||
const n = N - dim + j;
|
||||
if (size[j] > sizeMax[n]) {
|
||||
sizeMax[n] = size[j];
|
||||
}
|
||||
}
|
||||
}
|
||||
for (let 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
|
||||
*/
|
||||
function checkBroadcastingRules(size, toSize) {
|
||||
const N = toSize.length;
|
||||
const dim = size.length;
|
||||
for (let j = 0; j < dim; j++) {
|
||||
const 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 (${size}) not possible to broadcast dimension ${dim} with size ${size[j]} to size ${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
|
||||
*/
|
||||
function broadcastTo(array, toSize) {
|
||||
let Asize = arraySize(array);
|
||||
if ((0, _object.deepStrictEqual)(Asize, toSize)) {
|
||||
return array;
|
||||
}
|
||||
checkBroadcastingRules(Asize, toSize);
|
||||
const broadcastedSize = broadcastSizes(Asize, toSize);
|
||||
const N = broadcastedSize.length;
|
||||
const paddedSize = [...Array(N - Asize.length).fill(1), ...Asize];
|
||||
let 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 (let 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
|
||||
*/
|
||||
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];
|
||||
}
|
||||
const sizes = arrays.map(function (array) {
|
||||
return arraySize(array);
|
||||
});
|
||||
const broadcastedSize = broadcastSizes(...sizes);
|
||||
const 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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
function get(array, index) {
|
||||
if (!Array.isArray(array)) {
|
||||
throw new Error('Array expected');
|
||||
}
|
||||
const size = arraySize(array);
|
||||
if (index.length !== size.length) {
|
||||
throw new _DimensionError.DimensionError(index.length, size.length);
|
||||
}
|
||||
for (let 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.
|
||||
*/
|
||||
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
|
||||
*/
|
||||
function clone(array) {
|
||||
return (0, _extends2.default)([], array);
|
||||
}
|
||||
411
node_modules/mathjs/lib/cjs/utils/bignumber/bitwise.js
generated
vendored
Normal file
411
node_modules/mathjs/lib/cjs/utils/bignumber/bitwise.js
generated
vendored
Normal file
@@ -0,0 +1,411 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.bitAndBigNumber = bitAndBigNumber;
|
||||
exports.bitNotBigNumber = bitNotBigNumber;
|
||||
exports.bitOrBigNumber = bitOrBigNumber;
|
||||
exports.bitXor = bitXor;
|
||||
exports.bitwise = bitwise;
|
||||
exports.leftShiftBigNumber = leftShiftBigNumber;
|
||||
exports.rightArithShiftBigNumber = rightArithShiftBigNumber;
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
function bitAndBigNumber(x, y) {
|
||||
if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
|
||||
throw new Error('Integers expected in function bitAnd');
|
||||
}
|
||||
const 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
|
||||
*
|
||||
*/
|
||||
function bitNotBigNumber(x) {
|
||||
if (x.isFinite() && !x.isInteger()) {
|
||||
throw new Error('Integer expected in function bitNot');
|
||||
}
|
||||
const BigNumber = x.constructor;
|
||||
const prevPrec = BigNumber.precision;
|
||||
BigNumber.config({
|
||||
precision: 1E9
|
||||
});
|
||||
const 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
|
||||
*/
|
||||
function bitOrBigNumber(x, y) {
|
||||
if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
|
||||
throw new Error('Integers expected in function bitOr');
|
||||
}
|
||||
const BigNumber = x.constructor;
|
||||
if (x.isNaN() || y.isNaN()) {
|
||||
return new BigNumber(NaN);
|
||||
}
|
||||
const 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}
|
||||
*/
|
||||
function bitwise(x, y, func) {
|
||||
const BigNumber = x.constructor;
|
||||
let xBits, yBits;
|
||||
const xSign = +(x.s < 0);
|
||||
const ySign = +(y.s < 0);
|
||||
if (xSign) {
|
||||
xBits = decCoefficientToBinaryString(bitNotBigNumber(x));
|
||||
for (let i = 0; i < xBits.length; ++i) {
|
||||
xBits[i] ^= 1;
|
||||
}
|
||||
} else {
|
||||
xBits = decCoefficientToBinaryString(x);
|
||||
}
|
||||
if (ySign) {
|
||||
yBits = decCoefficientToBinaryString(bitNotBigNumber(y));
|
||||
for (let i = 0; i < yBits.length; ++i) {
|
||||
yBits[i] ^= 1;
|
||||
}
|
||||
} else {
|
||||
yBits = decCoefficientToBinaryString(y);
|
||||
}
|
||||
let minBits, maxBits, minSign;
|
||||
if (xBits.length <= yBits.length) {
|
||||
minBits = xBits;
|
||||
maxBits = yBits;
|
||||
minSign = xSign;
|
||||
} else {
|
||||
minBits = yBits;
|
||||
maxBits = xBits;
|
||||
minSign = ySign;
|
||||
}
|
||||
let shortLen = minBits.length;
|
||||
let longLen = maxBits.length;
|
||||
const expFuncVal = func(xSign, ySign) ^ 1;
|
||||
let outVal = new BigNumber(expFuncVal ^ 1);
|
||||
let twoPower = new BigNumber(1);
|
||||
const two = new BigNumber(2);
|
||||
const 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
|
||||
const a = x.d; // array with digits
|
||||
let r = a[0] + '';
|
||||
for (let i = 1; i < a.length; ++i) {
|
||||
let s = a[i] + '';
|
||||
for (let z = 7 - s.length; z--;) {
|
||||
s = '0' + s;
|
||||
}
|
||||
r += s;
|
||||
}
|
||||
let j = r.length;
|
||||
while (r.charAt(j) === '0') {
|
||||
j--;
|
||||
}
|
||||
let xe = x.e;
|
||||
let str = r.slice(0, j + 1 || 1);
|
||||
const 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
|
||||
const arr = [0];
|
||||
for (let i = 0; i < str.length;) {
|
||||
let arrL = arr.length;
|
||||
while (arrL--) {
|
||||
arr[arrL] *= 10;
|
||||
}
|
||||
arr[0] += parseInt(str.charAt(i++)); // convert to int
|
||||
for (let 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
|
||||
*
|
||||
*/
|
||||
function bitXor(x, y) {
|
||||
if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
|
||||
throw new Error('Integers expected in function bitXor');
|
||||
}
|
||||
const 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);
|
||||
}
|
||||
const 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`
|
||||
*
|
||||
*/
|
||||
function leftShiftBigNumber(x, y) {
|
||||
if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
|
||||
throw new Error('Integers expected in function leftShift');
|
||||
}
|
||||
const 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`
|
||||
*
|
||||
*/
|
||||
function rightArithShiftBigNumber(x, y) {
|
||||
if (x.isFinite() && !x.isInteger() || y.isFinite() && !y.isInteger()) {
|
||||
throw new Error('Integers expected in function rightArithShift');
|
||||
}
|
||||
const 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();
|
||||
}
|
||||
62
node_modules/mathjs/lib/cjs/utils/bignumber/constants.js
generated
vendored
Normal file
62
node_modules/mathjs/lib/cjs/utils/bignumber/constants.js
generated
vendored
Normal file
@@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createBigNumberTau = exports.createBigNumberPi = exports.createBigNumberPhi = exports.createBigNumberE = void 0;
|
||||
var _function = require("../function.js");
|
||||
/**
|
||||
* Calculate BigNumber e
|
||||
* @param {function} BigNumber BigNumber constructor
|
||||
* @returns {BigNumber} Returns e
|
||||
*/
|
||||
const createBigNumberE = exports.createBigNumberE = (0, _function.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
|
||||
*/
|
||||
const createBigNumberPhi = exports.createBigNumberPhi = (0, _function.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
|
||||
*/
|
||||
const createBigNumberPi = exports.createBigNumberPi = (0, _function.memoize)(function (BigNumber) {
|
||||
return BigNumber.acos(-1);
|
||||
}, {
|
||||
hasher
|
||||
});
|
||||
|
||||
/**
|
||||
* Calculate BigNumber tau, tau = 2 * pi
|
||||
* @param {function} BigNumber BigNumber constructor
|
||||
* @returns {BigNumber} Returns tau
|
||||
*/
|
||||
const createBigNumberTau = exports.createBigNumberTau = (0, _function.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;
|
||||
}
|
||||
251
node_modules/mathjs/lib/cjs/utils/bignumber/formatter.js
generated
vendored
Normal file
251
node_modules/mathjs/lib/cjs/utils/bignumber/formatter.js
generated
vendored
Normal file
@@ -0,0 +1,251 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.format = format;
|
||||
exports.toEngineering = toEngineering;
|
||||
exports.toExponential = toExponential;
|
||||
exports.toFixed = toFixed;
|
||||
var _is = require("../is.js");
|
||||
var _number = require("../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) {
|
||||
const BigNumberCtor = n.constructor;
|
||||
const big2 = new BigNumberCtor(2);
|
||||
let suffix = '';
|
||||
if (size) {
|
||||
if (size < 1) {
|
||||
throw new Error('size must be in greater than 0');
|
||||
}
|
||||
if (!(0, _number.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^${size - 1}, 2^${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${size}`;
|
||||
}
|
||||
switch (base) {
|
||||
case 2:
|
||||
return `${n.toBinary()}${suffix}`;
|
||||
case 8:
|
||||
return `${n.toOctal()}${suffix}`;
|
||||
case 16:
|
||||
return `${n.toHexadecimal()}${suffix}`;
|
||||
default:
|
||||
throw new Error(`Base ${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
|
||||
*/
|
||||
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';
|
||||
}
|
||||
const {
|
||||
notation,
|
||||
precision,
|
||||
wordSize
|
||||
} = (0, _number.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
|
||||
const lowerExp = _toNumberOrDefault(options === null || options === void 0 ? void 0 : options.lowerExp, -3);
|
||||
const 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
|
||||
let str;
|
||||
const rounded = value.toSignificantDigits(precision);
|
||||
const 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 () {
|
||||
const digits = arguments[2];
|
||||
const 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.
|
||||
*/
|
||||
function toEngineering(value, precision) {
|
||||
// find nearest lower multiple of 3 for exponent
|
||||
const e = value.e;
|
||||
const newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3;
|
||||
|
||||
// find difference in exponents, and calculate the value without exponent
|
||||
const valueWithoutExp = value.mul(Math.pow(10, -newExp));
|
||||
let valueStr = valueWithoutExp.toPrecision(precision);
|
||||
if (valueStr.includes('e')) {
|
||||
const 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
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
function toFixed(value, precision) {
|
||||
return value.toFixed(precision);
|
||||
}
|
||||
function _toNumberOrDefault(value, defaultValue) {
|
||||
if ((0, _is.isNumber)(value)) {
|
||||
return value;
|
||||
} else if ((0, _is.isBigNumber)(value)) {
|
||||
return value.toNumber();
|
||||
} else {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
45
node_modules/mathjs/lib/cjs/utils/bignumber/nearlyEqual.js
generated
vendored
Normal file
45
node_modules/mathjs/lib/cjs/utils/bignumber/nearlyEqual.js
generated
vendored
Normal file
@@ -0,0 +1,45 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.nearlyEqual = nearlyEqual;
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
function nearlyEqual(a, b) {
|
||||
let relTol = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1e-9;
|
||||
let 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));
|
||||
}
|
||||
186
node_modules/mathjs/lib/cjs/utils/collection.js
generated
vendored
Normal file
186
node_modules/mathjs/lib/cjs/utils/collection.js
generated
vendored
Normal file
@@ -0,0 +1,186 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.containsCollections = containsCollections;
|
||||
exports.deepForEach = deepForEach;
|
||||
exports.deepMap = deepMap;
|
||||
exports.reduce = reduce;
|
||||
exports.scatter = scatter;
|
||||
var _is = require("./is.js");
|
||||
var _IndexError = require("../error/IndexError.js");
|
||||
var _array = require("./array.js");
|
||||
var _switch2 = require("./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.
|
||||
*/
|
||||
function containsCollections(array) {
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
if ((0, _is.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
|
||||
*/
|
||||
function deepForEach(array, callback) {
|
||||
if ((0, _is.isMatrix)(array)) {
|
||||
array = array.valueOf();
|
||||
}
|
||||
for (let i = 0, ii = array.length; i < ii; i++) {
|
||||
const 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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
function reduce(mat, dim, callback) {
|
||||
const size = Array.isArray(mat) ? (0, _array.arraySize)(mat) : mat.size();
|
||||
if (dim < 0 || dim >= size.length) {
|
||||
// TODO: would be more clear when throwing a DimensionError here
|
||||
throw new _IndexError.IndexError(dim, size.length);
|
||||
}
|
||||
if ((0, _is.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) {
|
||||
let 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 = (0, _switch2._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
|
||||
function scatter(a, j, w, x, u, mark, cindex, f, inverse, update, value) {
|
||||
// a arrays
|
||||
const avalues = a._values;
|
||||
const aindex = a._index;
|
||||
const aptr = a._ptr;
|
||||
|
||||
// vars
|
||||
let 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
19
node_modules/mathjs/lib/cjs/utils/complex.js
generated
vendored
Normal file
19
node_modules/mathjs/lib/cjs/utils/complex.js
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.complexEquals = complexEquals;
|
||||
var _number = require("./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.
|
||||
*/
|
||||
function complexEquals(x, y, relTol, absTol) {
|
||||
return (0, _number.nearlyEqual)(x.re, y.re, relTol, absTol) && (0, _number.nearlyEqual)(x.im, y.im, relTol, absTol);
|
||||
}
|
||||
151
node_modules/mathjs/lib/cjs/utils/customs.js
generated
vendored
Normal file
151
node_modules/mathjs/lib/cjs/utils/customs.js
generated
vendored
Normal file
@@ -0,0 +1,151 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.getSafeMethod = getSafeMethod;
|
||||
exports.getSafeProperty = getSafeProperty;
|
||||
exports.isPlainObject = isPlainObject;
|
||||
exports.isSafeMethod = isSafeMethod;
|
||||
exports.isSafeProperty = isSafeProperty;
|
||||
exports.setSafeProperty = setSafeProperty;
|
||||
var _object = require("./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 ((0, _object.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 ((0, _object.hasOwnProperty)(object, method) && Object.getPrototypeOf && method in Object.getPrototypeOf(object)) {
|
||||
return false;
|
||||
}
|
||||
// SAFE: whitelisted
|
||||
// e.g toString
|
||||
if ((0, _object.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;
|
||||
}
|
||||
const safeNativeProperties = {
|
||||
length: true,
|
||||
name: true
|
||||
};
|
||||
const safeNativeMethods = {
|
||||
toString: true,
|
||||
valueOf: true,
|
||||
toLocaleString: true
|
||||
};
|
||||
24
node_modules/mathjs/lib/cjs/utils/emitter.js
generated
vendored
Normal file
24
node_modules/mathjs/lib/cjs/utils/emitter.js
generated
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.mixin = mixin;
|
||||
var _tinyEmitter = _interopRequireDefault(require("tiny-emitter"));
|
||||
/**
|
||||
* Extend given object with emitter functions `on`, `off`, `once`, `emit`
|
||||
* @param {Object} obj
|
||||
* @return {Object} obj
|
||||
*/
|
||||
function mixin(obj) {
|
||||
// create event emitter
|
||||
const emitter = new _tinyEmitter.default();
|
||||
|
||||
// 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;
|
||||
}
|
||||
137
node_modules/mathjs/lib/cjs/utils/factory.js
generated
vendored
Normal file
137
node_modules/mathjs/lib/cjs/utils/factory.js
generated
vendored
Normal file
@@ -0,0 +1,137 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.assertDependencies = assertDependencies;
|
||||
exports.create = create;
|
||||
exports.factory = factory;
|
||||
exports.isFactory = isFactory;
|
||||
exports.isOptionalDependency = isOptionalDependency;
|
||||
exports.sortFactories = sortFactories;
|
||||
exports.stripOptionalNotation = stripOptionalNotation;
|
||||
var _object = require("./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}
|
||||
*/
|
||||
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.
|
||||
const deps = (0, _object.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.
|
||||
*/
|
||||
function sortFactories(factories) {
|
||||
const 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;
|
||||
}
|
||||
const sorted = [];
|
||||
function addFactory(factory) {
|
||||
let 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
|
||||
function create(factories) {
|
||||
let 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}
|
||||
*/
|
||||
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
|
||||
*/
|
||||
function assertDependencies(name, dependencies, scope) {
|
||||
const allDefined = dependencies.filter(dependency => !isOptionalDependency(dependency)) // filter optionals
|
||||
.every(dependency => scope[dependency] !== undefined);
|
||||
if (!allDefined) {
|
||||
const 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 "${name}", ` + `some dependencies are missing: ${missingDependencies.map(d => `"${d}"`).join(', ')}.`);
|
||||
}
|
||||
}
|
||||
function isOptionalDependency(dependency) {
|
||||
return dependency && dependency[0] === '?';
|
||||
}
|
||||
function stripOptionalNotation(dependency) {
|
||||
return dependency && dependency[0] === '?' ? dependency.slice(1) : dependency;
|
||||
}
|
||||
92
node_modules/mathjs/lib/cjs/utils/function.js
generated
vendored
Normal file
92
node_modules/mathjs/lib/cjs/utils/function.js
generated
vendored
Normal file
@@ -0,0 +1,92 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.memoize = memoize;
|
||||
exports.memoizeCompare = memoizeCompare;
|
||||
var _lruQueue = require("./lruQueue.js");
|
||||
// function utils
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
function memoize(fn) {
|
||||
let {
|
||||
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: (0, _lruQueue.lruQueue)(limit || Number.POSITIVE_INFINITY)
|
||||
};
|
||||
}
|
||||
const args = [];
|
||||
for (let i = 0; i < arguments.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
const hash = hasher(args);
|
||||
if (memoize.cache.values.has(hash)) {
|
||||
memoize.cache.lru.hit(hash);
|
||||
return memoize.cache.values.get(hash);
|
||||
}
|
||||
const 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}
|
||||
*/
|
||||
function memoizeCompare(fn, isEqual) {
|
||||
const memoize = function memoize() {
|
||||
const args = [];
|
||||
for (let i = 0; i < arguments.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
for (let c = 0; c < memoize.cache.length; c++) {
|
||||
const 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;
|
||||
}
|
||||
}
|
||||
const res = fn.apply(fn, args);
|
||||
memoize.cache.unshift({
|
||||
args,
|
||||
res
|
||||
});
|
||||
return res;
|
||||
};
|
||||
memoize.cache = [];
|
||||
return memoize;
|
||||
}
|
||||
245
node_modules/mathjs/lib/cjs/utils/is.js
generated
vendored
Normal file
245
node_modules/mathjs/lib/cjs/utils/is.js
generated
vendored
Normal file
@@ -0,0 +1,245 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.isAccessorNode = isAccessorNode;
|
||||
exports.isArray = void 0;
|
||||
exports.isArrayNode = isArrayNode;
|
||||
exports.isAssignmentNode = isAssignmentNode;
|
||||
exports.isBigInt = isBigInt;
|
||||
exports.isBigNumber = isBigNumber;
|
||||
exports.isBlockNode = isBlockNode;
|
||||
exports.isBoolean = isBoolean;
|
||||
exports.isChain = isChain;
|
||||
exports.isCollection = isCollection;
|
||||
exports.isComplex = isComplex;
|
||||
exports.isConditionalNode = isConditionalNode;
|
||||
exports.isConstantNode = isConstantNode;
|
||||
exports.isDate = isDate;
|
||||
exports.isDenseMatrix = isDenseMatrix;
|
||||
exports.isFraction = isFraction;
|
||||
exports.isFunction = isFunction;
|
||||
exports.isFunctionAssignmentNode = isFunctionAssignmentNode;
|
||||
exports.isFunctionNode = isFunctionNode;
|
||||
exports.isHelp = isHelp;
|
||||
exports.isIndex = isIndex;
|
||||
exports.isIndexNode = isIndexNode;
|
||||
exports.isMap = isMap;
|
||||
exports.isMatrix = isMatrix;
|
||||
exports.isNode = isNode;
|
||||
exports.isNull = isNull;
|
||||
exports.isNumber = isNumber;
|
||||
exports.isObject = isObject;
|
||||
exports.isObjectNode = isObjectNode;
|
||||
exports.isObjectWrappingMap = isObjectWrappingMap;
|
||||
exports.isOperatorNode = isOperatorNode;
|
||||
exports.isParenthesisNode = isParenthesisNode;
|
||||
exports.isPartitionedMap = isPartitionedMap;
|
||||
exports.isRange = isRange;
|
||||
exports.isRangeNode = isRangeNode;
|
||||
exports.isRegExp = isRegExp;
|
||||
exports.isRelationalNode = isRelationalNode;
|
||||
exports.isResultSet = isResultSet;
|
||||
exports.isSparseMatrix = isSparseMatrix;
|
||||
exports.isString = isString;
|
||||
exports.isSymbolNode = isSymbolNode;
|
||||
exports.isUndefined = isUndefined;
|
||||
exports.isUnit = isUnit;
|
||||
exports.rule2Node = rule2Node;
|
||||
exports.typeOf = typeOf;
|
||||
var _map = require("./map.js");
|
||||
// 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.
|
||||
|
||||
function isNumber(x) {
|
||||
return typeof x === 'number';
|
||||
}
|
||||
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;
|
||||
}
|
||||
function isBigInt(x) {
|
||||
return typeof x === 'bigint';
|
||||
}
|
||||
function isComplex(x) {
|
||||
return x && typeof x === 'object' && Object.getPrototypeOf(x).isComplex === true || false;
|
||||
}
|
||||
function isFraction(x) {
|
||||
return x && typeof x === 'object' && Object.getPrototypeOf(x).isFraction === true || false;
|
||||
}
|
||||
function isUnit(x) {
|
||||
return x && x.constructor.prototype.isUnit === true || false;
|
||||
}
|
||||
function isString(x) {
|
||||
return typeof x === 'string';
|
||||
}
|
||||
const isArray = exports.isArray = Array.isArray;
|
||||
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
|
||||
*/
|
||||
function isCollection(x) {
|
||||
return Array.isArray(x) || isMatrix(x);
|
||||
}
|
||||
function isDenseMatrix(x) {
|
||||
return x && x.isDenseMatrix && x.constructor.prototype.isMatrix === true || false;
|
||||
}
|
||||
function isSparseMatrix(x) {
|
||||
return x && x.isSparseMatrix && x.constructor.prototype.isMatrix === true || false;
|
||||
}
|
||||
function isRange(x) {
|
||||
return x && x.constructor.prototype.isRange === true || false;
|
||||
}
|
||||
function isIndex(x) {
|
||||
return x && x.constructor.prototype.isIndex === true || false;
|
||||
}
|
||||
function isBoolean(x) {
|
||||
return typeof x === 'boolean';
|
||||
}
|
||||
function isResultSet(x) {
|
||||
return x && x.constructor.prototype.isResultSet === true || false;
|
||||
}
|
||||
function isHelp(x) {
|
||||
return x && x.constructor.prototype.isHelp === true || false;
|
||||
}
|
||||
function isFunction(x) {
|
||||
return typeof x === 'function';
|
||||
}
|
||||
function isDate(x) {
|
||||
return x instanceof Date;
|
||||
}
|
||||
function isRegExp(x) {
|
||||
return x instanceof RegExp;
|
||||
}
|
||||
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
|
||||
*/
|
||||
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 _map.ObjectWrappingMap || typeof object.set === 'function' && typeof object.get === 'function' && typeof object.keys === 'function' && typeof object.has === 'function';
|
||||
}
|
||||
function isPartitionedMap(object) {
|
||||
return isMap(object) && isMap(object.a) && isMap(object.b);
|
||||
}
|
||||
function isObjectWrappingMap(object) {
|
||||
return isMap(object) && isObject(object.wrappedObject);
|
||||
}
|
||||
function isNull(x) {
|
||||
return x === null;
|
||||
}
|
||||
function isUndefined(x) {
|
||||
return x === undefined;
|
||||
}
|
||||
function isAccessorNode(x) {
|
||||
return x && x.isAccessorNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isArrayNode(x) {
|
||||
return x && x.isArrayNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isAssignmentNode(x) {
|
||||
return x && x.isAssignmentNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isBlockNode(x) {
|
||||
return x && x.isBlockNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isConditionalNode(x) {
|
||||
return x && x.isConditionalNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
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.
|
||||
*/
|
||||
function rule2Node(node) {
|
||||
return isConstantNode(node) || isOperatorNode(node) && node.args.length === 1 && isConstantNode(node.args[0]) && '-+~'.includes(node.op);
|
||||
}
|
||||
function isFunctionAssignmentNode(x) {
|
||||
return x && x.isFunctionAssignmentNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isFunctionNode(x) {
|
||||
return x && x.isFunctionNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isIndexNode(x) {
|
||||
return x && x.isIndexNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isNode(x) {
|
||||
return x && x.isNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isObjectNode(x) {
|
||||
return x && x.isObjectNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isOperatorNode(x) {
|
||||
return x && x.isOperatorNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isParenthesisNode(x) {
|
||||
return x && x.isParenthesisNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isRangeNode(x) {
|
||||
return x && x.isRangeNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isRelationalNode(x) {
|
||||
return x && x.isRelationalNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isSymbolNode(x) {
|
||||
return x && x.isSymbolNode === true && x.constructor.prototype.isNode === true || false;
|
||||
}
|
||||
function isChain(x) {
|
||||
return x && x.constructor.prototype.isChain === true || false;
|
||||
}
|
||||
function typeOf(x) {
|
||||
const 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', ...
|
||||
}
|
||||
497
node_modules/mathjs/lib/cjs/utils/latex.js
generated
vendored
Normal file
497
node_modules/mathjs/lib/cjs/utils/latex.js
generated
vendored
Normal file
@@ -0,0 +1,497 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.defaultTemplate = void 0;
|
||||
exports.escapeLatex = escapeLatex;
|
||||
exports.latexSymbols = exports.latexOperators = exports.latexFunctions = void 0;
|
||||
exports.toSymbol = toSymbol;
|
||||
var _escapeLatex = _interopRequireDefault(require("escape-latex"));
|
||||
var _object = require("./object.js");
|
||||
/* eslint no-template-curly-in-string: "off" */
|
||||
|
||||
const latexSymbols = exports.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{?}'
|
||||
};
|
||||
const latexOperators = exports.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'
|
||||
};
|
||||
const latexFunctions = exports.latexFunctions = {
|
||||
// arithmetic
|
||||
abs: {
|
||||
1: '\\left|${args[0]}\\right|'
|
||||
},
|
||||
add: {
|
||||
2: `\\left(\${args[0]}${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]}${latexOperators.dotDivide}\${args[1]}\\right)`
|
||||
},
|
||||
dotMultiply: {
|
||||
2: `\\left(\${args[0]}${latexOperators.dotMultiply}\${args[1]}\\right)`
|
||||
},
|
||||
dotPow: {
|
||||
2: `\\left(\${args[0]}${latexOperators.dotPow}\${args[1]}\\right)`
|
||||
},
|
||||
exp: {
|
||||
1: '\\exp\\left(${args[0]}\\right)'
|
||||
},
|
||||
expm1: `\\left(e${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]}${latexOperators.mod}\${args[1]}\\right)`
|
||||
},
|
||||
multiply: {
|
||||
2: `\\left(\${args[0]}${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)${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]}${latexOperators.subtract}\${args[1]}\\right)`
|
||||
},
|
||||
unaryMinus: {
|
||||
1: `${latexOperators.unaryMinus}\\left(\${args[0]}\\right)`
|
||||
},
|
||||
unaryPlus: {
|
||||
1: `${latexOperators.unaryPlus}\\left(\${args[0]}\\right)`
|
||||
},
|
||||
// bitwise
|
||||
bitAnd: {
|
||||
2: `\\left(\${args[0]}${latexOperators.bitAnd}\${args[1]}\\right)`
|
||||
},
|
||||
bitNot: {
|
||||
1: latexOperators.bitNot + '\\left(${args[0]}\\right)'
|
||||
},
|
||||
bitOr: {
|
||||
2: `\\left(\${args[0]}${latexOperators.bitOr}\${args[1]}\\right)`
|
||||
},
|
||||
bitXor: {
|
||||
2: `\\left(\${args[0]}${latexOperators.bitXor}\${args[1]}\\right)`
|
||||
},
|
||||
leftShift: {
|
||||
2: `\\left(\${args[0]}${latexOperators.leftShift}\${args[1]}\\right)`
|
||||
},
|
||||
rightArithShift: {
|
||||
2: `\\left(\${args[0]}${latexOperators.rightArithShift}\${args[1]}\\right)`
|
||||
},
|
||||
rightLogShift: {
|
||||
2: `\\left(\${args[0]}${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]}${latexOperators.and}\${args[1]}\\right)`
|
||||
},
|
||||
not: {
|
||||
1: latexOperators.not + '\\left(${args[0]}\\right)'
|
||||
},
|
||||
or: {
|
||||
2: `\\left(\${args[0]}${latexOperators.or}\${args[1]}\\right)`
|
||||
},
|
||||
xor: {
|
||||
2: `\\left(\${args[0]}${latexOperators.xor}\${args[1]}\\right)`
|
||||
},
|
||||
// matrix
|
||||
cross: {
|
||||
2: '\\left(${args[0]}\\right)\\times\\left(${args[1]}\\right)'
|
||||
},
|
||||
ctranspose: {
|
||||
1: `\\left(\${args[0]}\\right)${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]}}${latexOperators.pow}{\\frac{1}{2}}`
|
||||
},
|
||||
trace: {
|
||||
1: '\\mathrm{tr}\\left(${args[0]}\\right)'
|
||||
},
|
||||
transpose: {
|
||||
1: `\\left(\${args[0]}\\right)${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)${latexOperators.factorial}`
|
||||
},
|
||||
gamma: {
|
||||
1: '\\Gamma\\left(${args[0]}\\right)'
|
||||
},
|
||||
lgamma: {
|
||||
1: '\\ln\\Gamma\\left(${args[0]}\\right)'
|
||||
},
|
||||
// relational
|
||||
equal: {
|
||||
2: `\\left(\${args[0]}${latexOperators.equal}\${args[1]}\\right)`
|
||||
},
|
||||
larger: {
|
||||
2: `\\left(\${args[0]}${latexOperators.larger}\${args[1]}\\right)`
|
||||
},
|
||||
largerEq: {
|
||||
2: `\\left(\${args[0]}${latexOperators.largerEq}\${args[1]}\\right)`
|
||||
},
|
||||
smaller: {
|
||||
2: `\\left(\${args[0]}${latexOperators.smaller}\${args[1]}\\right)`
|
||||
},
|
||||
smallerEq: {
|
||||
2: `\\left(\${args[0]}${latexOperators.smallerEq}\${args[1]}\\right)`
|
||||
},
|
||||
unequal: {
|
||||
2: `\\left(\${args[0]}${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]}${latexOperators.to}\${args[1]}\\right)`
|
||||
},
|
||||
// utils
|
||||
numeric: function (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)+${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)'
|
||||
}
|
||||
};
|
||||
const defaultTemplate = exports.defaultTemplate = '\\mathrm{${name}}\\left(${args}\\right)';
|
||||
const latexUnits = {
|
||||
deg: '^\\circ'
|
||||
};
|
||||
function escapeLatex(string) {
|
||||
return (0, _escapeLatex.default)(string, {
|
||||
preserveFormatting: true
|
||||
});
|
||||
}
|
||||
|
||||
// @param {string} name
|
||||
// @param {boolean} isUnit
|
||||
function toSymbol(name, isUnit) {
|
||||
isUnit = typeof isUnit === 'undefined' ? false : isUnit;
|
||||
if (isUnit) {
|
||||
if ((0, _object.hasOwnProperty)(latexUnits, name)) {
|
||||
return latexUnits[name];
|
||||
}
|
||||
return '\\mathrm{' + escapeLatex(name) + '}';
|
||||
}
|
||||
if ((0, _object.hasOwnProperty)(latexSymbols, name)) {
|
||||
return latexSymbols[name];
|
||||
}
|
||||
return escapeLatex(name);
|
||||
}
|
||||
22
node_modules/mathjs/lib/cjs/utils/log.js
generated
vendored
Normal file
22
node_modules/mathjs/lib/cjs/utils/log.js
generated
vendored
Normal file
@@ -0,0 +1,22 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.warnOnce = void 0;
|
||||
/**
|
||||
* Log a console.warn message only once
|
||||
*/
|
||||
const warnOnce = exports.warnOnce = (() => {
|
||||
const messages = {};
|
||||
return function warnOnce() {
|
||||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
args[_key] = arguments[_key];
|
||||
}
|
||||
const message = args.join(', ');
|
||||
if (!messages[message]) {
|
||||
messages[message] = true;
|
||||
console.warn('Warning:', ...args);
|
||||
}
|
||||
};
|
||||
})();
|
||||
57
node_modules/mathjs/lib/cjs/utils/lruQueue.js
generated
vendored
Normal file
57
node_modules/mathjs/lib/cjs/utils/lruQueue.js
generated
vendored
Normal file
@@ -0,0 +1,57 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.lruQueue = lruQueue;
|
||||
// (c) 2018, Mariusz Nowak
|
||||
// SPDX-License-Identifier: ISC
|
||||
// Derived from https://github.com/medikoo/lru-queue
|
||||
function lruQueue(limit) {
|
||||
let size = 0;
|
||||
let base = 1;
|
||||
let queue = Object.create(null);
|
||||
let map = Object.create(null);
|
||||
let index = 0;
|
||||
const del = function (id) {
|
||||
const 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 (id) {
|
||||
const oldIndex = map[id];
|
||||
const 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 () {
|
||||
size = index = 0;
|
||||
base = 1;
|
||||
queue = Object.create(null);
|
||||
map = Object.create(null);
|
||||
}
|
||||
};
|
||||
}
|
||||
214
node_modules/mathjs/lib/cjs/utils/map.js
generated
vendored
Normal file
214
node_modules/mathjs/lib/cjs/utils/map.js
generated
vendored
Normal file
@@ -0,0 +1,214 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.PartitionedMap = exports.ObjectWrappingMap = void 0;
|
||||
exports.assign = assign;
|
||||
exports.createEmptyMap = createEmptyMap;
|
||||
exports.createMap = createMap;
|
||||
exports.toObject = toObject;
|
||||
var _customs = require("./customs.js");
|
||||
var _is = require("./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.
|
||||
*/
|
||||
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 (0, _customs.getSafeProperty)(this.wrappedObject, key);
|
||||
}
|
||||
set(key, value) {
|
||||
(0, _customs.setSafeProperty)(this.wrappedObject, key, value);
|
||||
return this;
|
||||
}
|
||||
has(key) {
|
||||
return (0, _customs.isSafeProperty)(this.wrappedObject, key) && key in this.wrappedObject;
|
||||
}
|
||||
entries() {
|
||||
return mapIterator(this.keys(), key => [key, this.get(key)]);
|
||||
}
|
||||
forEach(callback) {
|
||||
for (const key of this.keys()) {
|
||||
callback(this.get(key), key, this);
|
||||
}
|
||||
}
|
||||
delete(key) {
|
||||
if ((0, _customs.isSafeProperty)(this.wrappedObject, key)) {
|
||||
delete this.wrappedObject[key];
|
||||
}
|
||||
}
|
||||
clear() {
|
||||
for (const 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`.
|
||||
*/
|
||||
exports.ObjectWrappingMap = ObjectWrappingMap;
|
||||
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 (const 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
|
||||
*/
|
||||
exports.PartitionedMap = PartitionedMap;
|
||||
function mapIterator(it, callback) {
|
||||
return {
|
||||
next: () => {
|
||||
const 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.
|
||||
*/
|
||||
function createEmptyMap() {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a Map from the given object.
|
||||
*
|
||||
* @param { Map | { [key: string]: unknown } | undefined } mapOrObject
|
||||
* @returns
|
||||
*/
|
||||
function createMap(mapOrObject) {
|
||||
if (!mapOrObject) {
|
||||
return createEmptyMap();
|
||||
}
|
||||
if ((0, _is.isMap)(mapOrObject)) {
|
||||
return mapOrObject;
|
||||
}
|
||||
if ((0, _is.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 }
|
||||
*/
|
||||
function toObject(map) {
|
||||
if (map instanceof ObjectWrappingMap) {
|
||||
return map.wrappedObject;
|
||||
}
|
||||
const object = {};
|
||||
for (const key of map.keys()) {
|
||||
const value = map.get(key);
|
||||
(0, _customs.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`.
|
||||
*/
|
||||
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 (const args of objects) {
|
||||
if (!args) {
|
||||
continue;
|
||||
}
|
||||
if ((0, _is.isMap)(args)) {
|
||||
for (const key of args.keys()) {
|
||||
map.set(key, args.get(key));
|
||||
}
|
||||
} else if ((0, _is.isObject)(args)) {
|
||||
for (const key of Object.keys(args)) {
|
||||
map.set(key, args[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
25
node_modules/mathjs/lib/cjs/utils/noop.js
generated
vendored
Normal file
25
node_modules/mathjs/lib/cjs/utils/noop.js
generated
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.noBignumber = noBignumber;
|
||||
exports.noFraction = noFraction;
|
||||
exports.noIndex = noIndex;
|
||||
exports.noMatrix = noMatrix;
|
||||
exports.noSubset = noSubset;
|
||||
function noBignumber() {
|
||||
throw new Error('No "bignumber" implementation available');
|
||||
}
|
||||
function noFraction() {
|
||||
throw new Error('No "fraction" implementation available');
|
||||
}
|
||||
function noMatrix() {
|
||||
throw new Error('No "matrix" implementation available');
|
||||
}
|
||||
function noIndex() {
|
||||
throw new Error('No "index" implementation available');
|
||||
}
|
||||
function noSubset() {
|
||||
throw new Error('No "matrix" implementation available');
|
||||
}
|
||||
761
node_modules/mathjs/lib/cjs/utils/number.js
generated
vendored
Normal file
761
node_modules/mathjs/lib/cjs/utils/number.js
generated
vendored
Normal file
@@ -0,0 +1,761 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.cbrt = exports.atanh = exports.asinh = exports.acosh = exports.DBL_EPSILON = void 0;
|
||||
exports.copysign = copysign;
|
||||
exports.cosh = void 0;
|
||||
exports.digits = digits;
|
||||
exports.expm1 = void 0;
|
||||
exports.format = format;
|
||||
exports.isInteger = isInteger;
|
||||
exports.isIntegerStr = isIntegerStr;
|
||||
exports.log2 = exports.log1p = exports.log10 = void 0;
|
||||
exports.nearlyEqual = nearlyEqual;
|
||||
exports.normalizeFormatOptions = normalizeFormatOptions;
|
||||
exports.roundDigits = roundDigits;
|
||||
exports.safeNumberType = safeNumberType;
|
||||
exports.sinh = exports.sign = void 0;
|
||||
exports.splitNumber = splitNumber;
|
||||
exports.tanh = void 0;
|
||||
exports.toEngineering = toEngineering;
|
||||
exports.toExponential = toExponential;
|
||||
exports.toFixed = toFixed;
|
||||
exports.toPrecision = toPrecision;
|
||||
var _is = require("./is.js");
|
||||
/**
|
||||
* @typedef {{sign: '+' | '-' | '', coefficients: number[], exponent: number}} SplitValue
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check if a number is integer
|
||||
* @param {number | boolean} value
|
||||
* @return {boolean} isInteger
|
||||
*/
|
||||
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
|
||||
*/
|
||||
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'}
|
||||
*/
|
||||
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}
|
||||
*/
|
||||
const sign = exports.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}
|
||||
*/
|
||||
const log2 = exports.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}
|
||||
*/
|
||||
const log10 = exports.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}
|
||||
*/
|
||||
const log1p = exports.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
|
||||
*/
|
||||
const cbrt = exports.cbrt = Math.cbrt || function cbrt(x) {
|
||||
if (x === 0) {
|
||||
return x;
|
||||
}
|
||||
const negate = x < 0;
|
||||
let 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
|
||||
*/
|
||||
const expm1 = exports.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) {
|
||||
const prefixes = {
|
||||
2: '0b',
|
||||
8: '0o',
|
||||
16: '0x'
|
||||
};
|
||||
const prefix = prefixes[base];
|
||||
let 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^${size - 1}, 2^${size - 1}-1]`);
|
||||
}
|
||||
if (!isInteger(n)) {
|
||||
throw new Error('Value must be an integer');
|
||||
}
|
||||
if (n < 0) {
|
||||
n = n + 2 ** size;
|
||||
}
|
||||
suffix = `i${size}`;
|
||||
}
|
||||
let sign = '';
|
||||
if (n < 0) {
|
||||
n = -n;
|
||||
sign = '-';
|
||||
}
|
||||
return `${sign}${prefix}${n.toString(base)}${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
|
||||
*/
|
||||
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';
|
||||
}
|
||||
const {
|
||||
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 () {
|
||||
const digits = arguments[2];
|
||||
const 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
|
||||
* }
|
||||
*/
|
||||
function normalizeFormatOptions(options) {
|
||||
// default values for options
|
||||
let notation = 'auto';
|
||||
let precision;
|
||||
let wordSize;
|
||||
if (options !== undefined) {
|
||||
if ((0, _is.isNumber)(options)) {
|
||||
precision = options;
|
||||
} else if ((0, _is.isBigNumber)(options)) {
|
||||
precision = options.toNumber();
|
||||
} else if ((0, _is.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
|
||||
*/
|
||||
function splitNumber(value) {
|
||||
// parse the input value
|
||||
const match = String(value).toLowerCase().match(/^(-?)(\d+\.?\d*)(e([+-]?\d+))?$/);
|
||||
if (!match) {
|
||||
throw new SyntaxError('Invalid number ' + value);
|
||||
}
|
||||
const sign = match[1];
|
||||
const digits = match[2];
|
||||
let exponent = parseFloat(match[4] || '0');
|
||||
const dot = digits.indexOf('.');
|
||||
exponent += dot !== -1 ? dot - 1 : digits.length - 1;
|
||||
const 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.
|
||||
*/
|
||||
function toEngineering(value, precision) {
|
||||
if (isNaN(value) || !isFinite(value)) {
|
||||
return String(value);
|
||||
}
|
||||
const split = splitNumber(value);
|
||||
const rounded = roundDigits(split, precision);
|
||||
const e = rounded.exponent;
|
||||
const c = rounded.coefficients;
|
||||
|
||||
// find nearest lower multiple of 3 for exponent
|
||||
const newExp = e % 3 === 0 ? e : e < 0 ? e - 3 - e % 3 : e - e % 3;
|
||||
if ((0, _is.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)
|
||||
const missingZeros = Math.abs(e - newExp) - (c.length - 1);
|
||||
for (let i = 0; i < missingZeros; i++) {
|
||||
c.push(0);
|
||||
}
|
||||
}
|
||||
|
||||
// find difference in exponents
|
||||
let expDiff = Math.abs(e - newExp);
|
||||
let 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
|
||||
const decimals = c.slice(decimalIdx).join('');
|
||||
const decimalVal = (0, _is.isNumber)(precision) && decimals.length || decimals.match(/[1-9]/) ? '.' + decimals : '';
|
||||
const 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.
|
||||
*/
|
||||
function toFixed(value, precision) {
|
||||
if (isNaN(value) || !isFinite(value)) {
|
||||
return String(value);
|
||||
}
|
||||
const splitValue = splitNumber(value);
|
||||
const rounded = typeof precision === 'number' ? roundDigits(splitValue, splitValue.exponent + 1 + precision) : splitValue;
|
||||
let c = rounded.coefficients;
|
||||
let p = rounded.exponent + 1; // exponent may have changed
|
||||
|
||||
// append zeros if needed
|
||||
const 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.
|
||||
*/
|
||||
function toExponential(value, precision) {
|
||||
if (isNaN(value) || !isFinite(value)) {
|
||||
return String(value);
|
||||
}
|
||||
|
||||
// round if needed, else create a clone
|
||||
const split = splitNumber(value);
|
||||
const rounded = precision ? roundDigits(split, precision) : split;
|
||||
let c = rounded.coefficients;
|
||||
const 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`
|
||||
const 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}
|
||||
*/
|
||||
function toPrecision(value, precision, options) {
|
||||
if (isNaN(value) || !isFinite(value)) {
|
||||
return String(value);
|
||||
}
|
||||
|
||||
// determine lower and upper bound for exponential notation.
|
||||
const lowerExp = _toNumberOrDefault(options === null || options === void 0 ? void 0 : options.lowerExp, -3);
|
||||
const upperExp = _toNumberOrDefault(options === null || options === void 0 ? void 0 : options.upperExp, 5);
|
||||
const split = splitNumber(value);
|
||||
const rounded = precision ? roundDigits(split, precision) : split;
|
||||
if (rounded.exponent < lowerExp || rounded.exponent >= upperExp) {
|
||||
// exponential notation
|
||||
return toExponential(value, precision);
|
||||
} else {
|
||||
let c = rounded.coefficients;
|
||||
const 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);
|
||||
const 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
|
||||
*/
|
||||
function roundDigits(split, precision) {
|
||||
// create a clone
|
||||
const rounded = {
|
||||
sign: split.sign,
|
||||
coefficients: split.coefficients,
|
||||
exponent: split.exponent
|
||||
};
|
||||
const c = rounded.coefficients;
|
||||
|
||||
// prepend zeros if needed
|
||||
while (precision <= 0) {
|
||||
c.unshift(0);
|
||||
rounded.exponent++;
|
||||
precision++;
|
||||
}
|
||||
if (c.length > precision) {
|
||||
const removed = c.splice(precision, c.length - precision);
|
||||
if (removed[0] >= 5) {
|
||||
let 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) {
|
||||
const arr = [];
|
||||
for (let 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
|
||||
*/
|
||||
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
|
||||
*/
|
||||
const DBL_EPSILON = exports.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
|
||||
*/
|
||||
function nearlyEqual(a, b) {
|
||||
let relTol = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1e-8;
|
||||
let 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}
|
||||
*/
|
||||
const acosh = exports.acosh = Math.acosh || function (x) {
|
||||
return Math.log(Math.sqrt(x * x - 1) + x);
|
||||
};
|
||||
const asinh = exports.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}
|
||||
*/
|
||||
const atanh = exports.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}
|
||||
*/
|
||||
const cosh = exports.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}
|
||||
*/
|
||||
const sinh = exports.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}
|
||||
*/
|
||||
const tanh = exports.tanh = Math.tanh || function (x) {
|
||||
const 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}
|
||||
*/
|
||||
function copysign(x, y) {
|
||||
const signx = x > 0 ? true : x < 0 ? false : 1 / x === Infinity;
|
||||
const signy = y > 0 ? true : y < 0 ? false : 1 / y === Infinity;
|
||||
return signx ^ signy ? -x : x;
|
||||
}
|
||||
function _toNumberOrThrow(value, onError) {
|
||||
if ((0, _is.isNumber)(value)) {
|
||||
return value;
|
||||
} else if ((0, _is.isBigNumber)(value)) {
|
||||
return value.toNumber();
|
||||
} else {
|
||||
onError();
|
||||
}
|
||||
}
|
||||
function _toNumberOrDefault(value, defaultValue) {
|
||||
if ((0, _is.isNumber)(value)) {
|
||||
return value;
|
||||
} else if ((0, _is.isBigNumber)(value)) {
|
||||
return value.toNumber();
|
||||
} else {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
395
node_modules/mathjs/lib/cjs/utils/object.js
generated
vendored
Normal file
395
node_modules/mathjs/lib/cjs/utils/object.js
generated
vendored
Normal file
@@ -0,0 +1,395 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.canDefineProperty = canDefineProperty;
|
||||
exports.clone = clone;
|
||||
exports.deepExtend = deepExtend;
|
||||
exports.deepFlatten = deepFlatten;
|
||||
exports.deepStrictEqual = deepStrictEqual;
|
||||
exports.extend = extend;
|
||||
exports.get = get;
|
||||
exports.hasOwnProperty = hasOwnProperty;
|
||||
exports.isLegacyFactory = isLegacyFactory;
|
||||
exports.lazy = lazy;
|
||||
exports.mapObject = mapObject;
|
||||
exports.pick = pick;
|
||||
exports.pickShallow = pickShallow;
|
||||
exports.set = set;
|
||||
exports.traverse = traverse;
|
||||
var _is = require("./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
|
||||
*/
|
||||
function clone(x) {
|
||||
const 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 ((0, _is.isBigNumber)(x)) return x; // bignumbers are immutable
|
||||
|
||||
// object
|
||||
if ((0, _is.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: ${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
|
||||
*/
|
||||
function mapObject(object, callback) {
|
||||
const clone = {};
|
||||
for (const 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
|
||||
*/
|
||||
function extend(a, b) {
|
||||
for (const 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}
|
||||
*/
|
||||
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 (const 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}
|
||||
*/
|
||||
function deepStrictEqual(a, b) {
|
||||
let 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
|
||||
*/
|
||||
function deepFlatten(nestedObject) {
|
||||
const flattenedObject = {};
|
||||
_deepFlatten(nestedObject, flattenedObject);
|
||||
return flattenedObject;
|
||||
}
|
||||
|
||||
// helper function used by deepFlatten
|
||||
function _deepFlatten(nestedObject, flattenedObject) {
|
||||
for (const prop in nestedObject) {
|
||||
if (hasOwnProperty(nestedObject, prop)) {
|
||||
const 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
|
||||
*/
|
||||
function canDefineProperty() {
|
||||
// test needed for broken IE8 implementation
|
||||
try {
|
||||
if (Object.defineProperty) {
|
||||
Object.defineProperty({}, 'x', {
|
||||
get: function () {
|
||||
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.
|
||||
*/
|
||||
function lazy(object, prop, valueResolver) {
|
||||
let _uninitialized = true;
|
||||
let _value;
|
||||
Object.defineProperty(object, prop, {
|
||||
get: function () {
|
||||
if (_uninitialized) {
|
||||
_value = valueResolver();
|
||||
_uninitialized = false;
|
||||
}
|
||||
return _value;
|
||||
},
|
||||
set: function (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
|
||||
*/
|
||||
function traverse(object, path) {
|
||||
if (path && typeof path === 'string') {
|
||||
return traverse(object, path.split('.'));
|
||||
}
|
||||
let obj = object;
|
||||
if (path) {
|
||||
for (let i = 0; i < path.length; i++) {
|
||||
const key = path[i];
|
||||
if (!(key in obj)) {
|
||||
obj[key] = {};
|
||||
}
|
||||
obj = obj[key];
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* A safe hasOwnProperty
|
||||
* @param {Object} object
|
||||
* @param {string} property
|
||||
*/
|
||||
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}
|
||||
*/
|
||||
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}
|
||||
*/
|
||||
function get(object, path) {
|
||||
if (typeof path === 'string') {
|
||||
if (isPath(path)) {
|
||||
return get(object, path.split('.'));
|
||||
} else {
|
||||
return object[path];
|
||||
}
|
||||
}
|
||||
let child = object;
|
||||
for (let i = 0; i < path.length; i++) {
|
||||
const 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}
|
||||
*/
|
||||
function set(object, path, value) {
|
||||
if (typeof path === 'string') {
|
||||
if (isPath(path)) {
|
||||
return set(object, path.split('.'), value);
|
||||
} else {
|
||||
object[path] = value;
|
||||
return object;
|
||||
}
|
||||
}
|
||||
let child = object;
|
||||
for (let i = 0; i < path.length - 1; i++) {
|
||||
const key = path[i];
|
||||
if (child[key] === undefined) {
|
||||
child[key] = {};
|
||||
}
|
||||
child = child[key];
|
||||
}
|
||||
if (path.length > 0) {
|
||||
const 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}
|
||||
*/
|
||||
function pick(object, properties, transform) {
|
||||
const copy = {};
|
||||
for (let i = 0; i < properties.length; i++) {
|
||||
const key = properties[i];
|
||||
const 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}
|
||||
*/
|
||||
function pickShallow(object, properties) {
|
||||
const copy = {};
|
||||
for (let i = 0; i < properties.length; i++) {
|
||||
const key = properties[i];
|
||||
const 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('.');
|
||||
}
|
||||
94
node_modules/mathjs/lib/cjs/utils/optimizeCallback.js
generated
vendored
Normal file
94
node_modules/mathjs/lib/cjs/utils/optimizeCallback.js
generated
vendored
Normal file
@@ -0,0 +1,94 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.optimizeCallback = optimizeCallback;
|
||||
var _typedFunction = _interopRequireDefault(require("typed-function"));
|
||||
var _array = require("./array.js");
|
||||
var _is = require("./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.
|
||||
*/
|
||||
function optimizeCallback(callback, array, name) {
|
||||
if (_typedFunction.default.isTypedFunction(callback)) {
|
||||
const firstIndex = (array.isMatrix ? array.size() : (0, _array.arraySize)(array)).map(() => 0);
|
||||
const firstValue = array.isMatrix ? array.get(firstIndex) : (0, _array.get)(array, firstIndex);
|
||||
const hasSingleSignature = Object.keys(callback.signatures).length === 1;
|
||||
const numberOfArguments = _findNumberOfArguments(callback, firstValue, firstIndex, array);
|
||||
const 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) {
|
||||
const testArgs = [value, index, array];
|
||||
for (let i = 3; i > 0; i--) {
|
||||
const args = testArgs.slice(0, i);
|
||||
if (_typedFunction.default.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') {
|
||||
const argsDesc = [];
|
||||
argsDesc.push(`value: ${(0, _is.typeOf)(args[0])}`);
|
||||
if (args.length >= 2) {
|
||||
argsDesc.push(`index: ${(0, _is.typeOf)(args[1])}`);
|
||||
}
|
||||
if (args.length >= 3) {
|
||||
argsDesc.push(`array: ${(0, _is.typeOf)(args[2])}`);
|
||||
}
|
||||
throw new TypeError(`Function ${mappingFnName} cannot apply callback arguments ` + `${callbackName}(${argsDesc.join(', ')}) at index ${JSON.stringify(args[1])}`);
|
||||
} else {
|
||||
throw new TypeError(`Function ${mappingFnName} cannot apply callback arguments ` + `to function ${callbackName}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
7
node_modules/mathjs/lib/cjs/utils/print.js
generated
vendored
Normal file
7
node_modules/mathjs/lib/cjs/utils/print.js
generated
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.printTemplate = void 0;
|
||||
const printTemplate = exports.printTemplate = /\$([\w.]+)/g;
|
||||
20
node_modules/mathjs/lib/cjs/utils/product.js
generated
vendored
Normal file
20
node_modules/mathjs/lib/cjs/utils/product.js
generated
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.product = product;
|
||||
/** @param {number} i
|
||||
* @param {number} n
|
||||
* @returns {number} product of i to n
|
||||
*/
|
||||
function product(i, n) {
|
||||
if (n < i) {
|
||||
return 1;
|
||||
}
|
||||
if (n === i) {
|
||||
return n;
|
||||
}
|
||||
const half = n + i >> 1; // divide (n + i) by 2 and truncate to integer
|
||||
return product(i, half) * product(half + 1, n);
|
||||
}
|
||||
23
node_modules/mathjs/lib/cjs/utils/scope.js
generated
vendored
Normal file
23
node_modules/mathjs/lib/cjs/utils/scope.js
generated
vendored
Normal file
@@ -0,0 +1,23 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createSubScope = createSubScope;
|
||||
var _map = require("./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}
|
||||
*/
|
||||
function createSubScope(parentScope, args) {
|
||||
return new _map.PartitionedMap(parentScope, new _map.ObjectWrappingMap(args), new Set(Object.keys(args)));
|
||||
}
|
||||
248
node_modules/mathjs/lib/cjs/utils/snapshot.js
generated
vendored
Normal file
248
node_modules/mathjs/lib/cjs/utils/snapshot.js
generated
vendored
Normal file
@@ -0,0 +1,248 @@
|
||||
"use strict";
|
||||
|
||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.createSnapshotFromFactories = createSnapshotFromFactories;
|
||||
exports.validateBundle = validateBundle;
|
||||
exports.validateTypeOf = void 0;
|
||||
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
|
||||
var _assert = _interopRequireDefault(require("assert"));
|
||||
var allIsFunctions = _interopRequireWildcard(require("./is.js"));
|
||||
var _create = require("../core/create.js");
|
||||
var _string = require("./string.js");
|
||||
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
|
||||
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
|
||||
const validateTypeOf = exports.validateTypeOf = allIsFunctions.typeOf;
|
||||
function validateBundle(expectedBundleStructure, bundle) {
|
||||
const 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 {
|
||||
const issues = [];
|
||||
|
||||
// see whether all expected functions and objects are there
|
||||
traverse(expectedBundleStructure, (expectedType, path) => {
|
||||
const actualValue = get(bundle, path);
|
||||
const actualType = validateTypeOf(actualValue);
|
||||
const message = actualType === 'undefined' ? 'Missing entry in bundle. ' + `Path: ${JSON.stringify(path)}, expected type: ${expectedType}, actual type: ${actualType}` : 'Unexpected entry type in bundle. ' + `Path: ${JSON.stringify(path)}, expected type: ${expectedType}, actual type: ${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) => {
|
||||
const actualType = validateTypeOf(actualValue);
|
||||
const 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;
|
||||
}
|
||||
const message = expectedType === 'undefined' ? 'Unknown entry in bundle. ' + 'Is there a new function added which is missing in this snapshot test? ' + `Path: ${JSON.stringify(path)}, expected type: ${expectedType}, actual type: ${actualType}` : 'Unexpected entry type in bundle. ' + `Path: ${JSON.stringify(path)}, expected type: ${expectedType}, actual type: ${actualType}`;
|
||||
if (actualType !== expectedType) {
|
||||
issues.push({
|
||||
actualType,
|
||||
expectedType,
|
||||
message
|
||||
});
|
||||
console.warn(message);
|
||||
}
|
||||
});
|
||||
|
||||
// assert on the first issue (if any)
|
||||
if (issues.length > 0) {
|
||||
const {
|
||||
actualType,
|
||||
expectedType,
|
||||
message
|
||||
} = issues[0];
|
||||
console.warn(`${issues.length} bundle issues found`);
|
||||
_assert.default.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}}
|
||||
*/
|
||||
function createSnapshotFromFactories(factories) {
|
||||
const math = (0, _create.create)(factories);
|
||||
const allFactoryFunctions = {};
|
||||
const allFunctionsConstantsClasses = {};
|
||||
const allFunctionsConstants = {};
|
||||
const allTransformFunctions = {};
|
||||
const allDependencyCollections = {};
|
||||
const allClasses = {};
|
||||
const allNodeClasses = {};
|
||||
Object.keys(factories).forEach(factoryName => {
|
||||
const factory = factories[factoryName];
|
||||
const name = factory.fn;
|
||||
const isTransformFunction = factory.meta && factory.meta.isTransformFunction;
|
||||
const isClass = !isLowerCase(name[0]) && validateTypeOf(math[name]) === 'function';
|
||||
const 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 ((0, _string.endsWith)(name, 'Node')) {
|
||||
allNodeClasses[name] = 'function';
|
||||
} else {
|
||||
allClasses[name] = 'function';
|
||||
}
|
||||
} else {
|
||||
allFunctionsConstants[name] = validateTypeOf(math[name]);
|
||||
}
|
||||
});
|
||||
let embeddedDocs = {};
|
||||
Object.keys(factories).forEach(factoryName => {
|
||||
const factory = factories[factoryName];
|
||||
const 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']);
|
||||
const allTypeChecks = {};
|
||||
Object.keys(allIsFunctions).forEach(name => {
|
||||
if (name.indexOf('is') === 0) {
|
||||
allTypeChecks[name] = 'function';
|
||||
}
|
||||
});
|
||||
const allErrorClasses = {
|
||||
ArgumentsError: 'function',
|
||||
DimensionError: 'function',
|
||||
IndexError: 'function'
|
||||
};
|
||||
const expectedInstanceStructure = {
|
||||
...allFunctionsConstantsClasses,
|
||||
on: 'function',
|
||||
off: 'function',
|
||||
once: 'function',
|
||||
emit: 'function',
|
||||
import: 'function',
|
||||
config: 'function',
|
||||
create: 'function',
|
||||
factory: 'function',
|
||||
...allTypeChecks,
|
||||
...allErrorClasses,
|
||||
expression: {
|
||||
transform: {
|
||||
...allTransformFunctions
|
||||
},
|
||||
mathWithTransform: {
|
||||
// note that we don't have classes here,
|
||||
// only functions and constants are allowed in the editor
|
||||
...exclude(allFunctionsConstants, ['chain']),
|
||||
config: 'function'
|
||||
}
|
||||
}
|
||||
};
|
||||
const expectedES6Structure = {
|
||||
// functions
|
||||
...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) {
|
||||
let callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (value, path) => {};
|
||||
let 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) {
|
||||
let child = object;
|
||||
for (let i = 0; i < path.length; i++) {
|
||||
const 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) {
|
||||
const strippedObject = (0, _extends2.default)({}, object);
|
||||
excludedProperties.forEach(excludedProperty => {
|
||||
delete strippedObject[excludedProperty];
|
||||
});
|
||||
return strippedObject;
|
||||
}
|
||||
function isLowerCase(text) {
|
||||
return typeof text === 'string' && text.toLowerCase() === text;
|
||||
}
|
||||
203
node_modules/mathjs/lib/cjs/utils/string.js
generated
vendored
Normal file
203
node_modules/mathjs/lib/cjs/utils/string.js
generated
vendored
Normal file
@@ -0,0 +1,203 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports.compareText = compareText;
|
||||
exports.endsWith = endsWith;
|
||||
exports.escape = escape;
|
||||
exports.format = format;
|
||||
exports.stringify = stringify;
|
||||
var _is = require("./is.js");
|
||||
var _number = require("./number.js");
|
||||
var _formatter = require("./bignumber/formatter.js");
|
||||
/**
|
||||
* Check if a text ends with a certain string.
|
||||
* @param {string} text
|
||||
* @param {string} search
|
||||
*/
|
||||
function endsWith(text, search) {
|
||||
const start = text.length - search.length;
|
||||
const 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
|
||||
*/
|
||||
function format(value, options) {
|
||||
const 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 (0, _number.format)(value, options);
|
||||
}
|
||||
if ((0, _is.isBigNumber)(value)) {
|
||||
return (0, _formatter.format)(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 ((0, _is.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 {
|
||||
const 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}
|
||||
*/
|
||||
function stringify(value) {
|
||||
const text = String(value);
|
||||
let escaped = '';
|
||||
let i = 0;
|
||||
while (i < text.length) {
|
||||
const c = text.charAt(i);
|
||||
escaped += c in controlCharacters ? controlCharacters[c] : c;
|
||||
i++;
|
||||
}
|
||||
return '"' + escaped + '"';
|
||||
}
|
||||
const controlCharacters = {
|
||||
'"': '\\"',
|
||||
'\\': '\\\\',
|
||||
'\b': '\\b',
|
||||
'\f': '\\f',
|
||||
'\n': '\\n',
|
||||
'\r': '\\r',
|
||||
'\t': '\\t'
|
||||
};
|
||||
|
||||
/**
|
||||
* Escape special HTML characters
|
||||
* @param {*} value
|
||||
* @return {string}
|
||||
*/
|
||||
function escape(value) {
|
||||
let text = String(value);
|
||||
text = text.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
|
||||
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)) {
|
||||
let str = '[';
|
||||
const len = array.length;
|
||||
for (let 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}
|
||||
*/
|
||||
function compareText(x, y) {
|
||||
// we don't want to convert numbers to string, only accept string input
|
||||
if (!(0, _is.isString)(x)) {
|
||||
throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + (0, _is.typeOf)(x) + ', index: 0)');
|
||||
}
|
||||
if (!(0, _is.isString)(y)) {
|
||||
throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + (0, _is.typeOf)(y) + ', index: 1)');
|
||||
}
|
||||
return x === y ? 0 : x > y ? 1 : -1;
|
||||
}
|
||||
26
node_modules/mathjs/lib/cjs/utils/switch.js
generated
vendored
Normal file
26
node_modules/mathjs/lib/cjs/utils/switch.js
generated
vendored
Normal file
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
exports._switch = _switch;
|
||||
/**
|
||||
* Transpose a matrix
|
||||
* @param {Array} mat
|
||||
* @returns {Array} ret
|
||||
* @private
|
||||
*/
|
||||
function _switch(mat) {
|
||||
const I = mat.length;
|
||||
const J = mat[0].length;
|
||||
let i, j;
|
||||
const ret = [];
|
||||
for (j = 0; j < J; j++) {
|
||||
const tmp = [];
|
||||
for (i = 0; i < I; i++) {
|
||||
tmp.push(mat[i][j]);
|
||||
}
|
||||
ret.push(tmp);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
Reference in New Issue
Block a user