code stringlengths 24 2.07M | docstring stringlengths 25 85.3k | func_name stringlengths 1 92 | language stringclasses 1
value | repo stringlengths 5 64 | path stringlengths 4 172 | url stringlengths 44 218 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
function AccessorNode(object, index) {
if (!(this instanceof AccessorNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
if (!type.isNode(object)) {
throw new TypeError('Node expected for parameter "object"');
}
if (!type.isIndexNode(index)) {
th... | @constructor AccessorNode
@extends {Node}
Access an object property or get a matrix subset
@param {Node} object The object from which to retrieve
a property or subset.
@param {IndexNode} index IndexNode containing ranges | AccessorNode | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function ArrayNode(items) {
if (!(this instanceof ArrayNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this.items = items || []; // validate input
if (!Array.isArray(this.items) || !this.items.every(type.isNode)) {
throw new TypeError('Array containing... | @constructor ArrayNode
@extends {Node}
Holds an 1-dimensional array with items
@param {Node[]} [items] 1 dimensional array with items | ArrayNode | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
deprecated = function deprecated() {
throw new Error('Property `ArrayNode.nodes` is deprecated, use `ArrayNode.items` instead');
} | @constructor ArrayNode
@extends {Node}
Holds an 1-dimensional array with items
@param {Node[]} [items] 1 dimensional array with items | deprecated | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function AssignmentNode(object, index, value) {
if (!(this instanceof AssignmentNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this.object = object;
this.index = value ? index : null;
this.value = value || index; // validate input
if (!type.isSymbol... | @constructor AssignmentNode
@extends {Node}
Define a symbol, like `a=3.2`, update a property like `a.b=3.2`, or
replace a subset of a matrix like `A[2,2]=42`.
Syntax:
new AssignmentNode(symbol, value)
new AssignmentNode(object, index, value)
Usage:
new AssignmentNode(new SymbolNode('a'), new ConstantNod... | AssignmentNode | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function needParenthesis(node, parenthesis) {
if (!parenthesis) {
parenthesis = 'keep';
}
var precedence = operators.getPrecedence(node, parenthesis);
var exprPrecedence = operators.getPrecedence(node.value, parenthesis);
return parenthesis === 'all' || exprPrecedence !== null && exprPreceden... | Create a clone of this node, a shallow copy
@return {AssignmentNode} | needParenthesis | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function BlockNode(blocks) {
if (!(this instanceof BlockNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
} // validate input, copy blocks
if (!Array.isArray(blocks)) throw new Error('Array expected');
this.blocks = blocks.map(function (block) {
var node =... | @constructor BlockNode
@extends {Node}
Holds a set with blocks
@param {Array.<{node: Node} | {node: Node, visible: boolean}>} blocks
An array with blocks, where a block is constructed as an Object
with properties block, which is a Node, and visible, which is
a boolean. The property visi... | BlockNode | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function ConditionalNode(condition, trueExpr, falseExpr) {
if (!(this instanceof ConditionalNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
if (!type.isNode(condition)) throw new TypeError('Parameter condition must be a Node');
if (!type.isNode(trueExpr)) thr... | A lazy evaluating conditional operator: 'condition ? trueExpr : falseExpr'
@param {Node} condition Condition, must result in a boolean
@param {Node} trueExpr Expression evaluated when condition is true
@param {Node} falseExpr Expression evaluated when condition is true
@constructor ConditionalNode
@extends {No... | ConditionalNode | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function testCondition(condition) {
if (typeof condition === 'number' || typeof condition === 'boolean' || typeof condition === 'string') {
return !!condition;
}
if (condition) {
if (type.isBigNumber(condition)) {
return !condition.isZero();
}
if (type.isComplex(condition))... | Test whether a condition is met
@param {*} condition
@returns {boolean} true if condition is true or non-zero, else false | testCondition | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function FunctionAssignmentNode(name, params, expr) {
if (!(this instanceof FunctionAssignmentNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
} // validate input
if (typeof name !== 'string') throw new TypeError('String expected for parameter "name"');
if (!Ar... | @constructor FunctionAssignmentNode
@extends {Node}
Function assignment
@param {string} name Function name
@param {string[] | Array.<{name: string, type: string}>} params
Array with function parameter names, or an
array with objects containing the... | FunctionAssignmentNode | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function needParenthesis(node, parenthesis) {
var precedence = operators.getPrecedence(node, parenthesis);
var exprPrecedence = operators.getPrecedence(node.expr, parenthesis);
return parenthesis === 'all' || exprPrecedence !== null && exprPrecedence <= precedence;
} | Is parenthesis needed?
@param {Node} node
@param {Object} parenthesis
@private | needParenthesis | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function IndexNode(dimensions, dotNotation) {
if (!(this instanceof IndexNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this.dimensions = dimensions;
this.dotNotation = dotNotation || false; // validate input
if (!isArray(dimensions) || !dimensions.ever... | @constructor IndexNode
@extends Node
Describes a subset of a matrix or an object property.
Cannot be used on its own, needs to be used within an AccessorNode or
AssignmentNode.
@param {Node[]} dimensions
@param {boolean} [dotNotation=false] Optional property describing whether
t... | IndexNode | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
deprecated = function deprecated() {
throw new Error('Property `IndexNode.object` is deprecated, use `IndexNode.fn` instead');
} | @constructor IndexNode
@extends Node
Describes a subset of a matrix or an object property.
Cannot be used on its own, needs to be used within an AccessorNode or
AssignmentNode.
@param {Node[]} dimensions
@param {boolean} [dotNotation=false] Optional property describing whether
t... | deprecated | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function createRange(start, end, step) {
return new Range(type.isBigNumber(start) ? start.toNumber() : start, type.isBigNumber(end) ? end.toNumber() : end, type.isBigNumber(step) ? step.toNumber() : step);
} | Get LaTeX representation
@param {Object} options
@return {string} str | createRange | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function ObjectNode(properties) {
if (!(this instanceof ObjectNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this.properties = properties || {}; // validate input
if (properties) {
if (!(_typeof(properties) === 'object') || !Object.keys(properties).ev... | @constructor ObjectNode
@extends {Node}
Holds an object with keys/values
@param {Object.<string, Node>} [properties] object with key/value pairs | ObjectNode | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function RangeNode(start, end, step) {
if (!(this instanceof RangeNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
} // validate inputs
if (!type.isNode(start)) throw new TypeError('Node expected');
if (!type.isNode(end)) throw new TypeError('Node expected');
... | @constructor RangeNode
@extends {Node}
create a range
@param {Node} start included lower-bound
@param {Node} end included upper-bound
@param {Node} [step] optional step | RangeNode | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function calculateNecessaryParentheses(node, parenthesis) {
var precedence = operators.getPrecedence(node, parenthesis);
var parens = {};
var startPrecedence = operators.getPrecedence(node.start, parenthesis);
parens.start = startPrecedence !== null && startPrecedence <= precedence || parenthesis === 'a... | Calculate the necessary parentheses
@param {Node} node
@param {string} parenthesis
@return {Object} parentheses
@private | calculateNecessaryParentheses | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function RelationalNode(conditionals, params) {
if (!(this instanceof RelationalNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
if (!Array.isArray(conditionals)) throw new TypeError('Parameter conditionals must be an array');
if (!Array.isArray(params)) throw... | A node representing a chained conditional expression, such as 'x > y > z'
@param {String[]} conditionals An array of conditional operators used to compare the parameters
@param {Node[]} params The parameters that will be compared
@constructor RelationalNode
@extends {Node} | RelationalNode | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function flatten(node) {
if (!node.args || node.args.length === 0) {
return node;
}
node.args = allChildren(node);
for (var i = 0; i < node.args.length; i++) {
flatten(node.args[i]);
}
} | Flatten all associative operators in an expression tree.
Assumes parentheses have already been removed. | flatten | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function allChildren(node) {
var op;
var children = [];
var findChildren = function findChildren(node) {
for (var i = 0; i < node.args.length; i++) {
var child = node.args[i];
if (type.isOperatorNode(child) && op === child.op) {
findChildren(child);
} else {
... | Get the children of a node as if it has been flattened.
TODO implement for FunctionNodes | allChildren | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
findChildren = function findChildren(node) {
for (var i = 0; i < node.args.length; i++) {
var child = node.args[i];
if (type.isOperatorNode(child) && op === child.op) {
findChildren(child);
} else {
children.push(child);
}
}
} | Get the children of a node as if it has been flattened.
TODO implement for FunctionNodes | findChildren | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function unflattenr(node) {
if (!node.args || node.args.length === 0) {
return;
}
var makeNode = createMakeNodeFunction(node);
var l = node.args.length;
for (var i = 0; i < l; i++) {
unflattenr(node.args[i]);
}
if (l > 2 && isAssociative(node)) {
var curnode = node.args.... | Unflatten all flattened operators to a right-heavy binary tree. | unflattenr | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function unflattenl(node) {
if (!node.args || node.args.length === 0) {
return;
}
var makeNode = createMakeNodeFunction(node);
var l = node.args.length;
for (var i = 0; i < l; i++) {
unflattenl(node.args[i]);
}
if (l > 2 && isAssociative(node)) {
var curnode = node.args.... | Unflatten all flattened operators to a left-heavy binary tree. | unflattenl | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function createMakeNodeFunction(node) {
if (type.isOperatorNode(node)) {
return function (args) {
try {
return new OperatorNode(node.op, node.fn, args, node.implicit);
} catch (err) {
console.error(err);
return [];
}
};
} else {
return func... | Unflatten all flattened operators to a left-heavy binary tree. | createMakeNodeFunction | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function simplifyCore(node) {
if (type.isOperatorNode(node) && node.isUnary()) {
var a0 = simplifyCore(node.args[0]);
if (node.op === '+') {
// unary plus
return a0;
}
if (node.op === '-') {
// unary minus
if (type.isOperatorNode(a0)) {
if (a0.isUn... | simplifyCore() performs single pass simplification suitable for
applications requiring ultimate performance. In contrast, simplify()
extends simplifyCore() with additional passes to provide deeper
simplification.
Syntax:
simplify.simplifyCore(expr)
Examples:
const f = math.parse('2 * 1 * x ^ (2 - 1)')
m... | simplifyCore | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _det(matrix, rows, cols) {
if (rows === 1) {
// this is a 1 x 1 matrix
return object.clone(matrix[0][0]);
} else if (rows === 2) {
// this is a 2 x 2 matrix
// the determinant of [a11,a12;a21,a22] is det = a11*a22-a21*a12
return subtract(multiply(matrix[0][0], matrix[1][1]... | Calculate the determinant of a matrix
@param {Array[]} matrix A square, two dimensional matrix
@param {number} rows Number of rows of the matrix (zero-based)
@param {number} cols Number of columns of the matrix (zero-based)
@returns {number} det
@private | _det | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
csTdfs = function csTdfs(j, k, w, head, next, post, stack) {
// variables
var top = 0; // place j on the stack
w[stack] = j; // while (stack is not empty)
while (top >= 0) {
// p = top of stack
var p = w[stack + top]; // i = youngest child of p
var i = w[head + p];
if (i === ... | Depth-first search and postorder of a tree rooted at node j
@param {Number} j The tree node
@param {Number} k
@param {Array} w The workspace array
@param {Number} head The index offset within the workspace for the head array
@param {Number} next The index offset ... | csTdfs | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
csMarked = function csMarked(w, j) {
// check node is marked
return w[j] < 0;
} | Checks if the node at w[j] is marked
@param {Array} w The array
@param {Number} j The array index
Reference: http://faculty.cse.tamu.edu/davis/publications.html | csMarked | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
csMark = function csMark(w, j) {
// mark w[j]
w[j] = csFlip(w[j]);
} | Marks the node at w[j]
@param {Array} w The array
@param {Number} j The array index
Reference: http://faculty.cse.tamu.edu/davis/publications.html | csMark | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _denseForwardSubstitution(m, b) {
// validate matrix and vector, return copy of column vector b
b = solveValidation(m, b, true); // column vector data
var bdata = b._data; // rows & columns
var rows = m._size[0];
var columns = m._size[1]; // result
var x = []; // data
var data =... | Solves the linear equation system by forwards substitution. Matrix must be a lower triangular matrix.
`L * x = b`
Syntax:
math.lsolve(L, b)
Examples:
const a = [[-2, 3], [2, 1]]
const b = [11, 9]
const x = lsolve(a, b) // [[-5.5], [20]]
See also:
lup, slu, usolve, lusolve
@param {Matrix, Array} ... | _denseForwardSubstitution | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _sparseForwardSubstitution(m, b) {
// validate matrix and vector, return copy of column vector b
b = solveValidation(m, b, true); // column vector data
var bdata = b._data; // rows & columns
var rows = m._size[0];
var columns = m._size[1]; // matrix arrays
var values = m._values;
... | Solves the linear equation system by forwards substitution. Matrix must be a lower triangular matrix.
`L * x = b`
Syntax:
math.lsolve(L, b)
Examples:
const a = [[-2, 3], [2, 1]]
const b = [11, 9]
const x = lsolve(a, b) // [[-5.5], [20]]
See also:
lup, slu, usolve, lusolve
@param {Matrix, Array} ... | _sparseForwardSubstitution | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _denseBackwardSubstitution(m, b) {
// validate matrix and vector, return copy of column vector b
b = solveValidation(m, b, true); // column vector data
var bdata = b._data; // rows & columns
var rows = m._size[0];
var columns = m._size[1]; // result
var x = []; // arrays
var dat... | Solves the linear equation system by backward substitution. Matrix must be an upper triangular matrix.
`U * x = b`
Syntax:
math.usolve(U, b)
Examples:
const a = [[-2, 3], [2, 1]]
const b = [11, 9]
const x = usolve(a, b) // [[8], [9]]
See also:
lup, slu, usolve, lusolve
@param {Matrix, Array} U ... | _denseBackwardSubstitution | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _sparseBackwardSubstitution(m, b) {
// validate matrix and vector, return copy of column vector b
b = solveValidation(m, b, true); // column vector data
var bdata = b._data; // rows & columns
var rows = m._size[0];
var columns = m._size[1]; // matrix arrays
var values = m._values;
... | Solves the linear equation system by backward substitution. Matrix must be an upper triangular matrix.
`U * x = b`
Syntax:
math.usolve(U, b)
Examples:
const a = [[-2, 3], [2, 1]]
const b = [11, 9]
const x = usolve(a, b) // [[8], [9]]
See also:
lup, slu, usolve, lusolve
@param {Matrix, Array} U ... | _sparseBackwardSubstitution | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function bigFactorial(n) {
if (n.isZero()) {
return new type.BigNumber(1); // 0! is per definition 1
}
var precision = config.precision + (Math.log(n.toNumber()) | 0);
var Big = type.BigNumber.clone({
precision: precision
});
var res = new Big(n);
var value = n.toNumber() - 1; /... | Calculate factorial for a BigNumber
@param {BigNumber} n
@returns {BigNumber} Returns the factorial of n | bigFactorial | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _column(value, column) {
// check dimensions
if (value.size().length !== 2) {
throw new Error('Only two dimensional matrix is supported');
}
validateIndex(column, value.size()[1]);
var rowRange = range(0, value.size()[0]);
var index = new MatrixIndex(rowRange, column);
return... | Retrieve a column of a matrix
@param {Matrix } value A matrix
@param {number} column The index of the column
@return {Matrix} The retrieved column | _column | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _map(array, callback) {
// figure out what number of arguments the callback function expects
var args = maxArgumentCount(callback);
var recurse = function recurse(value, index) {
if (Array.isArray(value)) {
return value.map(function (child, i) {
// we create a copy of the index array a... | Map for a multi dimensional array
@param {Array} array
@param {Function} callback
@return {Array}
@private | _map | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
recurse = function recurse(value, index) {
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));
});
} else {
// invoke the callback function with the righ... | Map for a multi dimensional array
@param {Array} array
@param {Function} callback
@return {Array}
@private | recurse | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _row(value, row) {
// check dimensions
if (value.size().length !== 2) {
throw new Error('Only two dimensional matrix is supported');
}
validateIndex(row, value.size()[0]);
var columnRange = range(0, value.size()[1]);
var index = new MatrixIndex(row, columnRange);
return value... | Retrieve a row of a matrix
@param {Matrix } value A matrix
@param {number} row The index of the row
@return {Matrix} The retrieved row | _row | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _compareText(x, y) {
// we don't want to convert numbers to string, only accept string input
if (!type.isString(x)) {
throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + _typeof(x) + ', index: 0)');
}
if (!type.i... | Compare two strings
@param {string} x
@param {string} y
@returns {number}
@private | _compareText | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _median(array) {
try {
array = flatten(array.valueOf());
var num = array.length;
if (num === 0) {
throw new Error('Cannot calculate median of an empty array');
}
if (num % 2 === 0) {
// even: return the average of the two middle values
var mid = num /... | Recursively calculate the median of an n-dimensional array
@param {Array} array
@return {Number} median
@private | _median | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _nmeanDim(array, dim) {
try {
var sum = reduce(array, dim, add);
var s = Array.isArray(array) ? size(array) : array.size();
return divide(sum, s[dim]);
} catch (err) {
throw improveErrorMessage(err, 'mean');
}
} | Calculate the mean value in an n-dimensional array, returning a
n-1 dimensional array
@param {Array} array
@param {number} dim
@return {number} mean
@private | _nmeanDim | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _mean(array) {
var sum = 0;
var num = 0;
deepForEach(array, function (value) {
try {
sum = add(sum, value);
num++;
} catch (err) {
throw improveErrorMessage(err, 'mean', value);
}
});
if (num === 0) {
throw new Error('Cannot calculate mean of... | Recursively calculate the mean value in an n-dimensional array
@param {Array} array
@return {number} mean
@private | _mean | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _smallest(x, y) {
try {
return smaller(x, y) ? x : y;
} catch (err) {
throw improveErrorMessage(err, 'min', y);
}
} | Return the smallest of two values
@param {*} x
@param {*} y
@returns {*} Returns x when x is smallest, or y when y is smallest
@private | _smallest | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _min(array) {
var min;
deepForEach(array, function (value) {
try {
if (isNaN(value) && typeof value === 'number') {
min = NaN;
} else if (min === undefined || smaller(value, min)) {
min = value;
}
} catch (err) {
throw improveErrorMessage(... | Recursively calculate the minimum value in an n-dimensional array
@param {Array} array
@return {number} min
@private | _min | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _std(array, normalization) {
if (array.length === 0) {
throw new SyntaxError('Function std requires one or more parameters (0 provided)');
}
try {
return sqrt(variance.apply(null, arguments));
} catch (err) {
if (err instanceof TypeError && err.message.indexOf(' var') !== -1)... | Compute the standard deviation of a matrix or a list with values.
The standard deviations is defined as the square root of the variance:
`std(A) = sqrt(var(A))`.
In case of a (multi dimensional) array or matrix, the standard deviation
over all elements will be calculated by default, unless an axis is specified
in whic... | _std | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function Parser() {
if (!(this instanceof Parser)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this.scope = {};
} | @constructor Parser
Parser contains methods to evaluate or parse expressions, and has a number
of convenience methods to get, set, and remove variables from memory. Parser
keeps a scope containing variables in memory, which is used for all
evaluations.
Methods:
const result = parser.eval(expr) // evaluate an expre... | Parser | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function create(config) {
// create a new math.js instance
var math = core.create(config);
math.create = create; // import data types, functions, constants, expression parser, etc.
math['import'](__webpack_require__(168));
return math;
} // return a new instance of math.js | math.js factory function. Creates a new instance of math.js
@param {Object} [config] Available configuration options:
{number} epsilon
Minimum relative difference between two
compared values, used by all comparison functions.
... | create | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function load(factory) {
if (!isFactory(factory)) {
throw new Error('Factory object with properties `type`, `name`, and `factory` expected');
}
var index = factories.indexOf(factory);
var instance;
if (index === -1) {
// doesn't yet exist
if (factory.math === true) {
// p... | Load a function or data type from a factory.
If the function or data type already exists, the existing instance is
returned.
@param {{type: string, name: string, factory: Function}} factory
@returns {*} | load | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function ok () {
return true;
} | typed-function
Type checking for JavaScript functions
https://github.com/josdejong/typed-function | ok | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function notOk () {
return false;
} | typed-function
Type checking for JavaScript functions
https://github.com/josdejong/typed-function | notOk | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function undef () {
return undefined;
} | typed-function
Type checking for JavaScript functions
https://github.com/josdejong/typed-function | undef | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function create () {
// data type tests
var _types = [
{ name: 'number', test: function (x) { return typeof x === 'number' } },
{ name: 'string', test: function (x) { return typeof x === 'string' } },
{ name: 'boolean', test: function (x) { return typeof x === 'boolean' } },
{ na... | @typedef {{
params: Param[],
fn: function
}} Signature
@typedef {{
types: Type[],
restParam: boolean
}} Param
@typedef {{
name: string,
typeIndex: number,
test: function,
conversion?: ConversionDef,
conversionIndex: number,
}} Type
@typedef {{
from: string,
to: string,
convert: function (*) :... | create | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function findTypeByName (typeName) {
var entry = findInArray(typed.types, function (entry) {
return entry.name === typeName;
});
if (entry) {
return entry;
}
if (typeName === 'any') { // special baked-in case 'any'
return anyType;
}
var hint = findInA... | Find the test function for a type
@param {String} typeName
@return {TypeDef} Returns the type definition when found,
Throws a TypeError otherwise | findTypeByName | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function findTypeIndex(type) {
if (type === anyType) {
return 999;
}
return typed.types.indexOf(type);
} | Find the index of a type definition. Handles special case 'any'
@param {TypeDef} type
@return {number} | findTypeIndex | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function findTypeName(value) {
var entry = findInArray(typed.types, function (entry) {
return entry.test(value);
});
if (entry) {
return entry.name;
}
throw new TypeError('Value has unknown type. Value: ' + value);
} | Find a type that matches a value.
@param {*} value
@return {string} Returns the name of the first type for which
the type test matches the value. | findTypeName | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function find (fn, signature) {
if (!fn.signatures) {
throw new TypeError('Function is no typed-function');
}
// normalize input
var arr;
if (typeof signature === 'string') {
arr = signature.split(',');
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[... | Find a specific signature from a (composed) typed function, for example:
typed.find(fn, ['number', 'string'])
typed.find(fn, 'number, string')
Function find only only works for exact matches.
@param {Function} fn A typed-function
@param {string | string[]} signature Signature to be found, can... | find | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function convert (value, type) {
var from = findTypeName(value);
// check conversion is needed
if (type === from) {
return value;
}
for (var i = 0; i < typed.conversions.length; i++) {
var conversion = typed.conversions[i];
if (conversion.from === from && conversi... | Convert a given value to another data type.
@param {*} value
@param {string} type | convert | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function stringifyParams (params) {
return params
.map(function (param) {
var typeNames = param.types.map(getTypeName);
return (param.restParam ? '...' : '') + typeNames.join('|');
})
.join(',');
} | Stringify parameters in a normalized way
@param {Param[]} params
@return {string} | stringifyParams | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function parseParam (param, conversions) {
var restParam = param.indexOf('...') === 0;
var types = (!restParam)
? param
: (param.length > 3)
? param.slice(3)
: 'any';
var typeNames = types.split('|').map(trim)
.filter(notEmpty)
.filt... | Parse a parameter, like "...number | boolean"
@param {string} param
@param {ConversionDef[]} conversions
@return {Param} param | parseParam | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function parseSignature (signature, fn, conversions) {
var params = [];
if (signature.trim() !== '') {
params = signature
.split(',')
.map(trim)
.map(function (param, index, array) {
var parsedParam = parseParam(param, conversions);
i... | Parse a signature with comma separated parameters,
like "number | boolean, ...string"
@param {string} signature
@param {function} fn
@param {ConversionDef[]} conversions
@return {Signature | null} signature | parseSignature | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function hasRestParam(params) {
var param = last(params)
return param ? param.restParam : false;
} | Test whether a set of params contains a restParam
@param {Param[]} params
@return {boolean} Returns true when the last parameter is a restParam | hasRestParam | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function hasConversions(param) {
return param.types.some(function (type) {
return type.conversion != null;
});
} | Test whether a parameter contains conversions
@param {Param} param
@return {boolean} Returns true when at least one of the parameters
contains a conversion. | hasConversions | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function compileTest(param) {
if (!param || param.types.length === 0) {
// nothing to do
return ok;
}
else if (param.types.length === 1) {
return findTypeByName(param.types[0].name).test;
}
else if (param.types.length === 2) {
var test0 = findTypeByName(para... | Create a type test for a single parameter, which can have one or multiple
types.
@param {Param} param
@return {function(x: *) : boolean} Returns a test function | compileTest | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function compileTests(params) {
var tests, test0, test1;
if (hasRestParam(params)) {
// variable arguments like '...number'
tests = initial(params).map(compileTest);
var varIndex = tests.length;
var lastTest = compileTest(last(params));
var testRestParam = function (... | Create a test for all parameters of a signature
@param {Param[]} params
@return {function(args: Array<*>) : boolean} | compileTests | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
testRestParam = function (args) {
for (var i = varIndex; i < args.length; i++) {
if (!lastTest(args[i])) {
return false;
}
}
return true;
} | Create a test for all parameters of a signature
@param {Param[]} params
@return {function(args: Array<*>) : boolean} | testRestParam | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function getParamAtIndex(signature, index) {
return index < signature.params.length
? signature.params[index]
: hasRestParam(signature.params)
? last(signature.params)
: null
} | Find the parameter at a specific index of a signature.
Handles rest parameters.
@param {Signature} signature
@param {number} index
@return {Param | null} Returns the matching parameter when found,
null otherwise. | getParamAtIndex | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function getExpectedTypeNames (signature, index, excludeConversions) {
var param = getParamAtIndex(signature, index);
var types = param
? excludeConversions
? param.types.filter(isExactType)
: param.types
: [];
return types.map(getTypeName);
... | Get all type names of a parameter
@param {Signature} signature
@param {number} index
@param {boolean} excludeConversions
@return {string[]} Returns an array with type names | getExpectedTypeNames | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function getTypeName(type) {
return type.name;
} | Returns the name of a type
@param {Type} type
@return {string} Returns the type name | getTypeName | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function isExactType(type) {
return type.conversion === null || type.conversion === undefined;
} | Test whether a type is an exact type or conversion
@param {Type} type
@return {boolean} Returns true when | isExactType | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function mergeExpectedParams(signatures, index) {
var typeNames = uniq(flatMap(signatures, function (signature) {
return getExpectedTypeNames(signature, index, false);
}));
return (typeNames.indexOf('any') !== -1) ? ['any'] : typeNames;
} | Helper function for creating error messages: create an array with
all available types on a specific argument index.
@param {Signature[]} signatures
@param {number} index
@return {string[]} Returns an array with available types | mergeExpectedParams | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function createError(name, args, signatures) {
var err, expected;
var _name = name || 'unnamed';
// test for wrong type at some index
var matchingSignatures = signatures;
var index;
for (index = 0; index < args.length; index++) {
var nextMatchingDefs = matchingSignatures.fil... | Create
@param {string} name The name of the function
@param {array.<*>} args The actual arguments passed to the function
@param {Signature[]} signatures A list with available signatures
@return {TypeError} Returns a type error with additional data
attached to it in the property... | createError | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function getLowestTypeIndex (param) {
var min = 999;
for (var i = 0; i < param.types.length; i++) {
if (isExactType(param.types[i])) {
min = Math.min(min, param.types[i].typeIndex);
}
}
return min;
} | Find the lowest index of all exact types of a parameter (no conversions)
@param {Param} param
@return {number} Returns the index of the lowest type in typed.types | getLowestTypeIndex | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function getLowestConversionIndex (param) {
var min = 999;
for (var i = 0; i < param.types.length; i++) {
if (!isExactType(param.types[i])) {
min = Math.min(min, param.types[i].conversionIndex);
}
}
return min;
} | Find the lowest index of the conversion of all types of the parameter
having a conversion
@param {Param} param
@return {number} Returns the lowest index of the conversions of this type | getLowestConversionIndex | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function compareParams (param1, param2) {
var c;
// compare having a rest parameter or not
c = param1.restParam - param2.restParam;
if (c !== 0) {
return c;
}
// compare having conversions or not
c = hasConversions(param1) - hasConversions(param2);
if (c !== 0) ... | Compare two params
@param {Param} param1
@param {Param} param2
@return {number} returns a negative number when param1 must get a lower
index than param2, a positive number when the opposite,
or zero when both are equal | compareParams | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function compareSignatures (signature1, signature2) {
var len = Math.min(signature1.params.length, signature2.params.length);
var i;
var c;
// compare whether the params have conversions at all or not
c = signature1.params.some(hasConversions) - signature2.params.some(hasConversions)
... | Compare two signatures
@param {Signature} signature1
@param {Signature} signature2
@return {number} returns a negative number when param1 must get a lower
index than param2, a positive number when the opposite,
or zero when both are equal | compareSignatures | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function filterConversions(conversions, typeNames) {
var matches = {};
conversions.forEach(function (conversion) {
if (typeNames.indexOf(conversion.from) === -1 &&
typeNames.indexOf(conversion.to) !== -1 &&
!matches[conversion.from]) {
matches[conversion.from] = co... | Get params containing all types that can be converted to the defined types.
@param {ConversionDef[]} conversions
@param {string[]} typeNames
@return {ConversionDef[]} Returns the conversions that are available
for every type (if any) | filterConversions | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function compileArgsPreprocessing(params, fn) {
var fnConvert = fn;
// TODO: can we make this wrapper function smarter/simpler?
if (params.some(hasConversions)) {
var restParam = hasRestParam(params);
var compiledConversions = params.map(compileArgConversion)
fnConvert = fun... | Preprocess arguments before calling the original function:
- if needed convert the parameters
- in case of rest parameters, move the rest parameters into an Array
@param {Param[]} params
@param {function} fn
@return {function} Returns a wrapped function | compileArgsPreprocessing | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function compileArgConversion(param) {
var test0, test1, conversion0, conversion1;
var tests = [];
var conversions = [];
param.types.forEach(function (type) {
if (type.conversion) {
tests.push(findTypeByName(type.conversion.from).test);
conversions.push(type.conversi... | Compile conversion for a parameter to the right type
@param {Param} param
@return {function} Returns the wrapped function that will convert arguments | compileArgConversion | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function createSignaturesMap(signatures) {
var signaturesMap = {};
signatures.forEach(function (signature) {
if (!signature.params.some(hasConversions)) {
splitParams(signature.params, true).forEach(function (params) {
signaturesMap[stringifyParams(params)] = signature.fn;
... | Convert an array with signatures into a map with signatures,
where signatures with union types are split into separate signatures
Throws an error when there are conflicting types
@param {Signature[]} signatures
@return {Object.<string, function>} Returns a map with signatures
as ... | createSignaturesMap | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function splitParams(params, ignoreConversionTypes) {
function _splitParams(params, index, types) {
if (index < params.length) {
var param = params[index]
var filteredTypes = ignoreConversionTypes
? param.types.filter(isExactType)
: param.types;
va... | Split params with union types in to separate params.
For example:
splitParams([['Array', 'Object'], ['string', 'RegExp'])
// returns:
// [
// ['Array', 'string'],
// ['Array', 'RegExp'],
// ['Object', 'string'],
// ['Object', 'RegExp']
// ]
@param {Param[]} params
@param {bool... | splitParams | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function _splitParams(params, index, types) {
if (index < params.length) {
var param = params[index]
var filteredTypes = ignoreConversionTypes
? param.types.filter(isExactType)
: param.types;
var typeGroups
if (param.restParam) {
/... | Split params with union types in to separate params.
For example:
splitParams([['Array', 'Object'], ['string', 'RegExp'])
// returns:
// [
// ['Array', 'string'],
// ['Array', 'RegExp'],
// ['Object', 'string'],
// ['Object', 'RegExp']
// ]
@param {Param[]} params
@param {bool... | _splitParams | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function hasConflictingParams(signature1, signature2) {
var ii = Math.max(signature1.params.length, signature2.params.length);
for (var i = 0; i < ii; i++) {
var typesNames1 = getExpectedTypeNames(signature1, i, true);
var typesNames2 = getExpectedTypeNames(signature2, i, true);
if... | Test whether two signatures have a conflicting signature
@param {Signature} signature1
@param {Signature} signature2
@return {boolean} Returns true when the signatures conflict, false otherwise. | hasConflictingParams | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function createTypedFunction(name, signaturesMap) {
if (Object.keys(signaturesMap).length === 0) {
throw new SyntaxError('No signatures provided');
}
// parse the signatures, and check for conflicts
var parsedSignatures = [];
Object.keys(signaturesMap)
.map(function (sig... | Create a typed function
@param {String} name The name for the typed function
@param {Object.<string, function>} signaturesMap
An object with one or
multiple signatures as key, and the
function correspo... | createTypedFunction | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
generic = function generic() {
'use strict';
for (var i = iStart; i < iEnd; i++) {
if (tests[i](arguments)) {
return fns[i].apply(null, arguments);
}
}
throw createError(name, arguments, signatures);
} | Create a typed function
@param {String} name The name for the typed function
@param {Object.<string, function>} signaturesMap
An object with one or
multiple signatures as key, and the
function correspo... | generic | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
fn = function fn(arg0, arg1) {
'use strict';
if (arguments.length === len0 && test00(arg0) && test01(arg1)) { return fn0.apply(null, arguments); }
if (arguments.length === len1 && test10(arg0) && test11(arg1)) { return fn1.apply(null, arguments); }
if (arguments.length === len2 && test2... | Create a typed function
@param {String} name The name for the typed function
@param {Object.<string, function>} signaturesMap
An object with one or
multiple signatures as key, and the
function correspo... | fn | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function notIgnore(typeName) {
return typed.ignore.indexOf(typeName) === -1;
} | Test whether a type should be NOT be ignored
@param {string} typeName
@return {boolean} | notIgnore | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function trim(str) {
return str.trim();
} | trim a string
@param {string} str
@return {string} | trim | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function notEmpty(str) {
return !!str;
} | Test whether a string is not empty
@param {string} str
@return {boolean} | notEmpty | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function notNull(value) {
return value !== null;
} | test whether a value is not strict equal to null
@param {*} value
@return {boolean} | notNull | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function isInvalidParam (param) {
return param.types.length === 0;
} | Test whether a parameter has no types defined
@param {Param} param
@return {boolean} | isInvalidParam | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function initial(arr) {
return arr.slice(0, arr.length - 1);
} | Return all but the last items of an array
@param {Array} arr
@return {Array} | initial | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function last(arr) {
return arr[arr.length - 1];
} | return the last item of an array
@param {Array} arr
@return {*} | last | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function slice(arr, start, end) {
return Array.prototype.slice.call(arr, start, end);
} | Slice an array or function Arguments
@param {Array | Arguments | IArguments} arr
@param {number} start
@param {number} [end]
@return {Array} | slice | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function contains(array, item) {
return array.indexOf(item) !== -1;
} | Test whether an array contains some item
@param {Array} array
@param {*} item
@return {boolean} Returns true if array contains item, false if not. | contains | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function hasOverlap(array1, array2) {
for (var i = 0; i < array1.length; i++) {
if (contains(array2, array1[i])) {
return true;
}
}
return false;
} | Test whether two arrays have overlapping items
@param {Array} array1
@param {Array} array2
@return {boolean} Returns true when at least one item exists in both arrays | hasOverlap | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function findInArray(arr, test) {
for (var i = 0; i < arr.length; i++) {
if (test(arr[i])) {
return arr[i];
}
}
return undefined;
} | Return the first item from an array for which test(arr[i]) returns true
@param {Array} arr
@param {function} test
@return {* | undefined} Returns the first matching item
or undefined when there is no match | findInArray | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function uniq(arr) {
var entries = {}
for (var i = 0; i < arr.length; i++) {
entries[arr[i]] = true;
}
return Object.keys(entries);
} | Filter unique items of an array with strings
@param {string[]} arr
@return {string[]} | uniq | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function flatMap(arr, callback) {
return Array.prototype.concat.apply([], arr.map(callback));
} | Flat map the result invoking a callback for every item in an array.
https://gist.github.com/samgiles/762ee337dff48623e729
@param {Array} arr
@param {function} callback
@return {Array} | flatMap | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function getName (fns) {
var name = '';
for (var i = 0; i < fns.length; i++) {
var fn = fns[i];
// check whether the names are the same when defined
if ((typeof fn.signatures === 'object' || typeof fn.signature === 'string') && fn.name !== '') {
if (name === '') {
... | Retrieve the function name from a set of typed functions,
and check whether the name of all functions match (if given)
@param {function[]} fns | getName | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function extractSignatures(fns) {
var err;
var signaturesMap = {};
function validateUnique(_signature, _fn) {
if (signaturesMap.hasOwnProperty(_signature) && _fn !== signaturesMap[_signature]) {
err = new Error('Signature "' + _signature + '" is defined twice');
err.data =... | Retrieve the function name from a set of typed functions,
and check whether the name of all functions match (if given)
@param {function[]} fns | extractSignatures | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
function validateUnique(_signature, _fn) {
if (signaturesMap.hasOwnProperty(_signature) && _fn !== signaturesMap[_signature]) {
err = new Error('Signature "' + _signature + '" is defined twice');
err.data = {signature: _signature};
throw err;
// else: both signatures poin... | Retrieve the function name from a set of typed functions,
and check whether the name of all functions match (if given)
@param {function[]} fns | validateUnique | javascript | grimalschi/calque | math.js | https://github.com/grimalschi/calque/blob/master/math.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.