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)) { throw new TypeError('IndexNode expected for parameter "index"'); } this.object = object || null; this.index = index; // readonly property name Object.defineProperty(this, 'name', { get: function () { if (this.index) { return this.index.isObjectProperty() ? this.index.getObjectProperty() : ''; } else { return this.object.name || ''; } }.bind(this), set: function set() { throw new Error('Cannot assign a new name, name is read-only'); } }); }
@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 Nodes expected'); } // TODO: deprecated since v3, remove some day var deprecated = function deprecated() { throw new Error('Property `ArrayNode.nodes` is deprecated, use `ArrayNode.items` instead'); }; Object.defineProperty(this, 'nodes', { get: deprecated, set: deprecated }); }
@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.isSymbolNode(object) && !type.isAccessorNode(object)) { throw new TypeError('SymbolNode or AccessorNode expected as "object"'); } if (type.isSymbolNode(object) && object.name === 'end') { throw new Error('Cannot assign to symbol "end"'); } if (this.index && !type.isIndexNode(this.index)) { // index is optional throw new TypeError('IndexNode expected as "index"'); } if (!type.isNode(this.value)) { throw new TypeError('Node expected as "value"'); } // readonly property name Object.defineProperty(this, 'name', { get: function () { if (this.index) { return this.index.isObjectProperty() ? this.index.getObjectProperty() : ''; } else { return this.object.name || ''; } }.bind(this), set: function set() { throw new Error('Cannot assign a new name, name is read-only'); } }); }
@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 ConstantNode(2)) // a=2 new AssignmentNode(new SymbolNode('a'), new IndexNode('b'), new ConstantNode(2)) // a.b=2 new AssignmentNode(new SymbolNode('a'), new IndexNode(1, 2), new ConstantNode(3)) // a[1,2]=3 @param {SymbolNode | AccessorNode} object Object on which to assign a value @param {IndexNode} [index=null] Index, property name or matrix index. Optional. If not provided and `object` is a SymbolNode, the property is assigned to the global scope. @param {Node} value The value to be assigned
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 && exprPrecedence <= precedence; }
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 = block && block.node; var visible = block && block.visible !== undefined ? block.visible : true; if (!type.isNode(node)) throw new TypeError('Property "node" must be a Node'); if (typeof visible !== 'boolean') throw new TypeError('Property "visible" must be a boolean'); return { node: node, visible: visible }; }); }
@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 visible is optional and is true by default
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)) throw new TypeError('Parameter trueExpr must be a Node'); if (!type.isNode(falseExpr)) throw new TypeError('Parameter falseExpr must be a Node'); this.condition = condition; this.trueExpr = trueExpr; this.falseExpr = falseExpr; }
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 {Node}
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)) { return !!(condition.re || condition.im); } if (type.isUnit(condition)) { return !!condition.value; } } if (condition === null || condition === undefined) { return false; } throw new TypeError('Unsupported type of condition "' + mathTypeOf(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 (!Array.isArray(params)) throw new TypeError('Array containing strings or objects expected for parameter "params"'); if (!type.isNode(expr)) throw new TypeError('Node expected for parameter "expr"'); if (name in keywords) throw new Error('Illegal function name, "' + name + '" is a reserved keyword'); this.name = name; this.params = params.map(function (param) { return param && param.name || param; }); this.types = params.map(function (param) { return param && param.type || 'any'; }); this.expr = expr; }
@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 name and type of the parameter @param {Node} expr The function expression
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.every(type.isNode)) { throw new TypeError('Array containing Nodes expected for parameter "dimensions"'); } if (this.dotNotation && !this.isObjectProperty()) { throw new Error('dotNotation only applicable for object properties'); } // TODO: deprecated since v3, remove some day var deprecated = function deprecated() { throw new Error('Property `IndexNode.object` is deprecated, use `IndexNode.fn` instead'); }; Object.defineProperty(this, 'object', { get: deprecated, set: deprecated }); }
@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 this index was written using dot notation like `a.b`, or using bracket notation like `a["b"]` (default). Used to stringify an IndexNode.
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 this index was written using dot notation like `a.b`, or using bracket notation like `a["b"]` (default). Used to stringify an IndexNode.
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).every(function (key) { return type.isNode(properties[key]); })) { throw new TypeError('Object containing Nodes expected'); } } }
@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'); if (step && !type.isNode(step)) throw new TypeError('Node expected'); if (arguments.length > 3) throw new Error('Too many arguments'); this.start = start; // included lower-bound this.end = end; // included upper-bound this.step = step || null; // optional step }
@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 === 'all'; if (node.step) { var stepPrecedence = operators.getPrecedence(node.step, parenthesis); parens.step = stepPrecedence !== null && stepPrecedence <= precedence || parenthesis === 'all'; } var endPrecedence = operators.getPrecedence(node.end, parenthesis); parens.end = endPrecedence !== null && endPrecedence <= precedence || parenthesis === 'all'; return parens; }
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 new TypeError('Parameter params must be an array'); if (conditionals.length !== params.length - 1) throw new TypeError('Parameter params must contain exactly one more element than parameter conditionals'); this.conditionals = conditionals; this.params = params; }
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 { children.push(child); } } }; if (isAssociative(node)) { op = node.op; findChildren(node); return children; } else { return node.args; } }
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.pop(); while (node.args.length > 0) { curnode = makeNode([node.args.pop(), curnode]); } node.args = curnode.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.shift(); while (node.args.length > 0) { curnode = makeNode([curnode, node.args.shift()]); } node.args = curnode.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 function (args) { return new FunctionNode(new SymbolNode(node.name), args); }; } }
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.isUnary() && a0.op === '-') { return a0.args[0]; } else if (a0.isBinary() && a0.fn === 'subtract') { return new OperatorNode('-', 'subtract', [a0.args[1], a0.args[0]]); } } return new OperatorNode(node.op, node.fn, [a0]); } } else if (type.isOperatorNode(node) && node.isBinary()) { var _a = simplifyCore(node.args[0]); var a1 = simplifyCore(node.args[1]); if (node.op === '+') { if (type.isConstantNode(_a)) { if (isZero(_a.value)) { return a1; } else if (type.isConstantNode(a1)) { return new ConstantNode(add(_a.value, a1.value)); } } if (type.isConstantNode(a1) && isZero(a1.value)) { return _a; } if (type.isOperatorNode(a1) && a1.isUnary() && a1.op === '-') { return new OperatorNode('-', 'subtract', [_a, a1.args[0]]); } return new OperatorNode(node.op, node.fn, a1 ? [_a, a1] : [_a]); } else if (node.op === '-') { if (type.isConstantNode(_a) && a1) { if (type.isConstantNode(a1)) { return new ConstantNode(subtract(_a.value, a1.value)); } else if (isZero(_a.value)) { return new OperatorNode('-', 'unaryMinus', [a1]); } } // if (node.fn === "subtract" && node.args.length === 2) { if (node.fn === 'subtract') { if (type.isConstantNode(a1) && isZero(a1.value)) { return _a; } if (type.isOperatorNode(a1) && a1.isUnary() && a1.op === '-') { return simplifyCore(new OperatorNode('+', 'add', [_a, a1.args[0]])); } return new OperatorNode(node.op, node.fn, [_a, a1]); } } else if (node.op === '*') { if (type.isConstantNode(_a)) { if (isZero(_a.value)) { return node0; } else if (equal(_a.value, 1)) { return a1; } else if (type.isConstantNode(a1)) { return new ConstantNode(multiply(_a.value, a1.value)); } } if (type.isConstantNode(a1)) { if (isZero(a1.value)) { return node0; } else if (equal(a1.value, 1)) { return _a; } else if (type.isOperatorNode(_a) && _a.isBinary() && _a.op === node.op) { var a00 = _a.args[0]; if (type.isConstantNode(a00)) { var a00a1 = new ConstantNode(multiply(a00.value, a1.value)); return new OperatorNode(node.op, node.fn, [a00a1, _a.args[1]], node.implicit); // constants on left } } return new OperatorNode(node.op, node.fn, [a1, _a], node.implicit); // constants on left } return new OperatorNode(node.op, node.fn, [_a, a1], node.implicit); } else if (node.op === '/') { if (type.isConstantNode(_a)) { if (isZero(_a.value)) { return node0; } else if (type.isConstantNode(a1) && (equal(a1.value, 1) || equal(a1.value, 2) || equal(a1.value, 4))) { return new ConstantNode(divide(_a.value, a1.value)); } } return new OperatorNode(node.op, node.fn, [_a, a1]); } else if (node.op === '^') { if (type.isConstantNode(a1)) { if (isZero(a1.value)) { return node1; } else if (equal(a1.value, 1)) { return _a; } else { if (type.isConstantNode(_a)) { // fold constant return new ConstantNode(pow(_a.value, a1.value)); } else if (type.isOperatorNode(_a) && _a.isBinary() && _a.op === '^') { var a01 = _a.args[1]; if (type.isConstantNode(a01)) { return new OperatorNode(node.op, node.fn, [_a.args[0], new ConstantNode(multiply(a01.value, a1.value))]); } } } } return new OperatorNode(node.op, node.fn, [_a, a1]); } } else if (type.isParenthesisNode(node)) { var c = simplifyCore(node.content); if (type.isParenthesisNode(c) || type.isSymbolNode(c) || type.isConstantNode(c)) { return c; } return new ParenthesisNode(c); } else if (type.isFunctionNode(node)) { var args = node.args.map(simplifyCore).map(function (arg) { return type.isParenthesisNode(arg) ? arg.content : arg; }); return new FunctionNode(simplifyCore(node.fn), args); } else {// cannot simplify } return node; }
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)') math.simplify.simpifyCore(f) // Node {2 * x} math.simplify('2 * 1 * x ^ (2 - 1)', [math.simplify.simpifyCore]) // Node {2 * x} See also: derivative @param {Node} node The expression to be simplified
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]), multiply(matrix[1][0], matrix[0][1])); } else { // Compute the LU decomposition var decomp = lup(matrix); // The determinant is the product of the diagonal entries of U (and those of L, but they are all 1) var _det2 = decomp.U[0][0]; for (var _i = 1; _i < rows; _i++) { _det2 = multiply(_det2, decomp.U[_i][_i]); } // The determinant will be multiplied by 1 or -1 depending on the parity of the permutation matrix. // This can be determined by counting the cycles. This is roughly a linear time algorithm. var evenCycles = 0; var i = 0; var visited = []; while (true) { while (visited[i]) { i++; } if (i >= rows) break; var j = i; var cycleLen = 0; while (!visited[decomp.p[j]]) { visited[decomp.p[j]] = true; j = decomp.p[j]; cycleLen++; } if (cycleLen % 2 === 0) { evenCycles++; } } return evenCycles % 2 === 0 ? _det2 : unaryMinus(_det2); } }
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 === -1) { // p has no unordered children left top--; // node p is the kth postordered node post[k++] = p; } else { // remove i from children of p w[head + p] = w[next + i]; // increment top ++top; // start dfs on child node i w[stack + top] = i; } } return k; }
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 within the workspace for the next array @param {Array} post The post ordering array @param {Number} stack The index offset within the workspace for the stack array Reference: http://faculty.cse.tamu.edu/davis/publications.html
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 = m._data; // forward solve m * x = b, loop columns for (var j = 0; j < columns; j++) { // b[j] var bj = bdata[j][0] || 0; // x[j] var xj = void 0; // forward substitution (outer product) avoids inner looping when bj === 0 if (!equalScalar(bj, 0)) { // value @ [j, j] var vjj = data[j][j]; // check vjj if (equalScalar(vjj, 0)) { // system cannot be solved throw new Error('Linear system cannot be solved since matrix is singular'); } // calculate xj xj = divideScalar(bj, vjj); // loop rows for (var i = j + 1; i < rows; i++) { // update copy of b bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, data[i][j]))]; } } else { // zero @ j xj = 0; } // update x x[j] = [xj]; } // return vector return new DenseMatrix({ data: x, size: [rows, 1] }); }
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} L A N x N matrix or array (L) @param {Matrix, Array} b A column vector with the b values @return {DenseMatrix | Array} A column vector with the linear system solution (x)
_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; var index = m._index; var ptr = m._ptr; // vars var i, k; // result var x = []; // forward solve m * x = b, loop columns for (var j = 0; j < columns; j++) { // b[j] var bj = bdata[j][0] || 0; // forward substitution (outer product) avoids inner looping when bj === 0 if (!equalScalar(bj, 0)) { // value @ [j, j] var vjj = 0; // lower triangular matrix values & index (column j) var jvalues = []; var jindex = []; // last index in column var l = ptr[j + 1]; // values in column, find value @ [j, j] for (k = ptr[j]; k < l; k++) { // row i = index[k]; // check row (rows are not sorted!) if (i === j) { // update vjj vjj = values[k]; } else if (i > j) { // store lower triangular jvalues.push(values[k]); jindex.push(i); } } // at this point we must have a value @ [j, j] if (equalScalar(vjj, 0)) { // system cannot be solved, there is no value @ [j, j] throw new Error('Linear system cannot be solved since matrix is singular'); } // calculate xj var xj = divideScalar(bj, vjj); // loop lower triangular for (k = 0, l = jindex.length; k < l; k++) { // row i = jindex[k]; // update copy of b bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, jvalues[k]))]; } // update x x[j] = [xj]; } else { // update x x[j] = [0]; } } // return vector return new DenseMatrix({ data: x, size: [rows, 1] }); }
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} L A N x N matrix or array (L) @param {Matrix, Array} b A column vector with the b values @return {DenseMatrix | Array} A column vector with the linear system solution (x)
_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 data = m._data; // backward solve m * x = b, loop columns (backwards) for (var j = columns - 1; j >= 0; j--) { // b[j] var bj = bdata[j][0] || 0; // x[j] var xj = void 0; // backward substitution (outer product) avoids inner looping when bj === 0 if (!equalScalar(bj, 0)) { // value @ [j, j] var vjj = data[j][j]; // check vjj if (equalScalar(vjj, 0)) { // system cannot be solved throw new Error('Linear system cannot be solved since matrix is singular'); } // calculate xj xj = divideScalar(bj, vjj); // loop rows for (var i = j - 1; i >= 0; i--) { // update copy of b bdata[i] = [subtract(bdata[i][0] || 0, multiplyScalar(xj, data[i][j]))]; } } else { // zero value @ j xj = 0; } // update x x[j] = [xj]; } // return column vector return new DenseMatrix({ data: x, size: [rows, 1] }); }
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 A N x N matrix or array (U) @param {Matrix, Array} b A column vector with the b values @return {DenseMatrix | Array} A column vector with the linear system solution (x)
_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; var index = m._index; var ptr = m._ptr; // vars var i, k; // result var x = []; // backward solve m * x = b, loop columns (backwards) for (var j = columns - 1; j >= 0; j--) { // b[j] var bj = bdata[j][0] || 0; // backward substitution (outer product) avoids inner looping when bj === 0 if (!equalScalar(bj, 0)) { // value @ [j, j] var vjj = 0; // upper triangular matrix values & index (column j) var jvalues = []; var jindex = []; // first & last indeces in column var f = ptr[j]; var l = ptr[j + 1]; // values in column, find value @ [j, j], loop backwards for (k = l - 1; k >= f; k--) { // row i = index[k]; // check row if (i === j) { // update vjj vjj = values[k]; } else if (i < j) { // store upper triangular jvalues.push(values[k]); jindex.push(i); } } // at this point we must have a value @ [j, j] if (equalScalar(vjj, 0)) { // system cannot be solved, there is no value @ [j, j] throw new Error('Linear system cannot be solved since matrix is singular'); } // calculate xj var xj = divideScalar(bj, vjj); // loop upper triangular for (k = 0, l = jindex.length; k < l; k++) { // row i = jindex[k]; // update copy of b bdata[i] = [subtract(bdata[i][0], multiplyScalar(xj, jvalues[k]))]; } // update x x[j] = [xj]; } else { // update x x[j] = [0]; } } // return vector return new DenseMatrix({ data: x, size: [rows, 1] }); }
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 A N x N matrix or array (U) @param {Matrix, Array} b A column vector with the b values @return {DenseMatrix | Array} A column vector with the linear system solution (x)
_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; // number while (value > 1) { res = res.times(value); value--; } return new type.BigNumber(res.toPrecision(type.BigNumber.precision)); }
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 value.subset(index); }
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 and append the new index value return recurse(child, index.concat(i)); }); } else { // invoke the callback function with the right number of arguments if (args === 1) { return callback(value); } else if (args === 2) { return callback(value, index); } else { // 3 or -1 return callback(value, index, array); } } }; return recurse(array, []); }
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 right number of arguments if (args === 1) { return callback(value); } else if (args === 2) { return callback(value, index); } else { // 3 or -1 return callback(value, index, array); } } }
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.subset(index); }
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.isString(y)) { throw new TypeError('Unexpected type of argument in function compareText ' + '(expected: string or Array or Matrix, actual: ' + _typeof(y) + ', index: 1)'); } return x === y ? 0 : x > y ? 1 : -1; }
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 / 2 - 1; var right = partitionSelect(array, mid + 1); // array now partitioned at mid + 1, take max of left part var left = array[mid]; for (var i = 0; i < mid; ++i) { if (compare(array[i], left) > 0) { left = array[i]; } } return middle2(left, right); } else { // odd: return the middle value var m = partitionSelect(array, (num - 1) / 2); return middle(m); } } catch (err) { throw improveErrorMessage(err, 'median'); } } // helper function to type check the middle value of the array
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 an empty array'); } return divide(sum, num); }
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(err, 'min', value); } }); if (min === undefined) { throw new Error('Cannot calculate min of an empty array'); } return min; }
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) { throw new TypeError(err.message.replace(' var', ' std')); } else { throw err; } } }
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 which case the standard deviation will be computed along that axis. Additionally, it is possible to compute the standard deviation along the rows or columns of a matrix by specifying the dimension as the second argument. Optionally, the type of normalization can be specified as the final parameter. The parameter `normalization` can be one of the following values: - 'unbiased' (default) The sum of squared errors is divided by (n - 1) - 'uncorrected' The sum of squared errors is divided by n - 'biased' The sum of squared errors is divided by (n + 1) Syntax: math.std(a, b, c, ...) math.std(A) math.std(A, normalization) math.std(A, dimension) math.std(A, dimension, normalization) Examples: math.std(2, 4, 6) // returns 2 math.std([2, 4, 6, 8]) // returns 2.581988897471611 math.std([2, 4, 6, 8], 'uncorrected') // returns 2.23606797749979 math.std([2, 4, 6, 8], 'biased') // returns 2 math.std([[1, 2, 3], [4, 5, 6]]) // returns 1.8708286933869707 math.std([[1, 2, 3], [4, 6, 8]], 0) // returns [2.1213203435596424, 2.8284271247461903, 3.5355339059327378] math.std([[1, 2, 3], [4, 6, 8]], 1) // returns [1, 2] math.std([[1, 2, 3], [4, 6, 8]], 1, 'biased') // returns [0.7071067811865476, 1.4142135623730951] See also: mean, median, max, min, prod, sum, var @param {Array | Matrix} array A single matrix or or multiple scalar values @param {string} [normalization='unbiased'] Determines how to normalize the variance. Choose 'unbiased' (default), 'uncorrected', or 'biased'. @param dimension {number | BigNumber} Determines the axis to compute the standard deviation for a matrix @return {*} The standard deviation
_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 expression const value = parser.get(name) // retrieve a variable from the parser const values = parser.getAll() // retrieve all defined variables parser.set(name, value) // set a variable in the parser parser.remove(name) // clear a variable from the // parsers scope parser.clear() // clear the parsers scope Example usage: const parser = new Parser() // Note: there is a convenience method which can be used instead: // const parser = new math.parser() // evaluate expressions parser.eval('sqrt(3^2 + 4^2)') // 5 parser.eval('sqrt(-4)') // 2i parser.eval('2 inch in cm') // 5.08 cm parser.eval('cos(45 deg)') // 0.7071067811865476 // define variables and functions parser.eval('x = 7 / 2') // 3.5 parser.eval('x + 3') // 6.5 parser.eval('function f(x, y) = x^y') // f(x, y) parser.eval('f(2, 3)') // 8 // get and set variables and functions const x = parser.get('x') // 7 const f = parser.get('f') // function const g = f(3, 2) // 9 parser.set('h', 500) const i = parser.eval('h / 2') // 250 parser.set('hello', function (name) { return 'hello, ' + name + '!' }) parser.eval('hello("user")') // "hello, user!" // clear defined functions and variables parser.clear()
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. {string} matrix A string 'matrix' (default) or 'array'. {string} number A string 'number' (default), 'bignumber', or 'fraction' {number} precision The number of significant digits for BigNumbers. Not applicable for Numbers. {boolean} predictable Predictable output type of functions. When true, output type depends only on the input types. When false (default), output type can vary depending on input values. For example `math.sqrt(-4)` returns `complex('2i')` when predictable is false, and returns `NaN` when true.
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) { // pass with math namespace instance = factory.factory(math.type, _config, load, math.typed, math); } else { instance = factory.factory(math.type, _config, load, math.typed); } // append to the cache factories.push(factory); instances.push(instance); } else { // already existing function, return the cached instance instance = instances[index]; } return instance; } // load the import and config functions
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' } }, { name: 'Function', test: function (x) { return typeof x === 'function'} }, { name: 'Array', test: Array.isArray }, { name: 'Date', test: function (x) { return x instanceof Date } }, { name: 'RegExp', test: function (x) { return x instanceof RegExp } }, { name: 'Object', test: function (x) { return typeof x === 'object' && x.constructor === Object }}, { name: 'null', test: function (x) { return x === null } }, { name: 'undefined', test: function (x) { return x === undefined } } ]; var anyType = { name: 'any', test: ok } // types which need to be ignored var _ignore = []; // type conversions var _conversions = []; // This is a temporary object, will be replaced with a typed function at the end var typed = { types: _types, conversions: _conversions, ignore: _ignore }; /** * Find the test function for a type * @param {String} typeName * @return {TypeDef} Returns the type definition when found, * Throws a TypeError otherwise */ 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 = findInArray(typed.types, function (entry) { return entry.name.toLowerCase() === typeName.toLowerCase(); }); throw new TypeError('Unknown type "' + typeName + '"' + (hint ? ('. Did you mean "' + hint.name + '"?') : '')); } /** * Find the index of a type definition. Handles special case 'any' * @param {TypeDef} type * @return {number} */ function findTypeIndex(type) { if (type === anyType) { return 999; } return typed.types.indexOf(type); } /** * 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. */ 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 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 be * an array or a comma separated string. * @return {Function} Returns the matching signature, or * throws an error when no signature * is found. */ 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[i].trim(); } } else if (Array.isArray(signature)) { arr = signature; } else { throw new TypeError('String array or a comma separated string expected'); } var str = arr.join(','); // find an exact match var match = fn.signatures[str]; if (match) { return match; } // TODO: extend find to match non-exact signatures throw new TypeError('Signature not found (signature: ' + (fn.name || 'unnamed') + '(' + arr.join(', ') + '))'); } /** * Convert a given value to another data type. * @param {*} value * @param {string} type */ 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 && conversion.to === type) { return conversion.convert(value); } } throw new Error('Cannot convert from ' + from + ' to ' + type); } /** * Stringify parameters in a normalized way * @param {Param[]} params * @return {string} */ function stringifyParams (params) { return params .map(function (param) { var typeNames = param.types.map(getTypeName); return (param.restParam ? '...' : '') + typeNames.join('|'); }) .join(','); } /** * Parse a parameter, like "...number | boolean" * @param {string} param * @param {ConversionDef[]} conversions * @return {Param} param */ 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) .filter(notIgnore); var matchingConversions = filterConversions(conversions, typeNames); var exactTypes = typeNames.map(function (typeName) { var type = findTypeByName(typeName); return { name: typeName, typeIndex: findTypeIndex(type), test: type.test, conversion: null, conversionIndex: -1 }; }); var convertibleTypes = matchingConversions.map(function (conversion) { var type = findTypeByName(conversion.from); return { name: conversion.from, typeIndex: findTypeIndex(type), test: type.test, conversion: conversion, conversionIndex: conversions.indexOf(conversion) }; }); return { types: exactTypes.concat(convertibleTypes), restParam: restParam }; } /** * Parse a signature with comma separated parameters, * like "number | boolean, ...string" * @param {string} signature * @param {function} fn * @param {ConversionDef[]} conversions * @return {Signature | null} signature */ 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); if (parsedParam.restParam && (index !== array.length - 1)) { throw new SyntaxError('Unexpected rest parameter "' + param + '": ' + 'only allowed for the last parameter'); } return parsedParam; }); } if (params.some(isInvalidParam)) { // invalid signature: at least one parameter has no types // (they may have been filtered) return null; } return { params: params, fn: fn }; } /** * Test whether a set of params contains a restParam * @param {Param[]} params * @return {boolean} Returns true when the last parameter is a restParam */ function hasRestParam(params) { var param = last(params) return param ? param.restParam : false; } /** * Test whether a parameter contains conversions * @param {Param} param * @return {boolean} Returns true when at least one of the parameters * contains a conversion. */ function hasConversions(param) { return param.types.some(function (type) { return type.conversion != null; }); } /** * 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 */ 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(param.types[0].name).test; var test1 = findTypeByName(param.types[1].name).test; return function or(x) { return test0(x) || test1(x); } } else { // param.types.length > 2 var tests = param.types.map(function (type) { return findTypeByName(type.name).test; }) return function or(x) { for (var i = 0; i < tests.length; i++) { if (tests[i](x)) { return true; } } return false; } } } /** * Create a test for all parameters of a signature * @param {Param[]} params * @return {function(args: Array<*>) : boolean} */ 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 (args) { for (var i = varIndex; i < args.length; i++) { if (!lastTest(args[i])) { return false; } } return true; } return function testArgs(args) { for (var i = 0; i < tests.length; i++) { if (!tests[i](args[i])) { return false; } } return testRestParam(args) && (args.length >= varIndex + 1); }; } else { // no variable arguments if (params.length === 0) { return function testArgs(args) { return args.length === 0; }; } else if (params.length === 1) { test0 = compileTest(params[0]); return function testArgs(args) { return test0(args[0]) && args.length === 1; }; } else if (params.length === 2) { test0 = compileTest(params[0]); test1 = compileTest(params[1]); return function testArgs(args) { return test0(args[0]) && test1(args[1]) && args.length === 2; }; } else { // arguments.length > 2 tests = params.map(compileTest); return function testArgs(args) { for (var i = 0; i < tests.length; i++) { if (!tests[i](args[i])) { return false; } } return args.length === tests.length; }; } } } /** * 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. */ function getParamAtIndex(signature, index) { return index < signature.params.length ? signature.params[index] : hasRestParam(signature.params) ? last(signature.params) : null } /** * Get all type names of a parameter * @param {Signature} signature * @param {number} index * @param {boolean} excludeConversions * @return {string[]} Returns an array with type names */ function getExpectedTypeNames (signature, index, excludeConversions) { var param = getParamAtIndex(signature, index); var types = param ? excludeConversions ? param.types.filter(isExactType) : param.types : []; return types.map(getTypeName); } /** * Returns the name of a type * @param {Type} type * @return {string} Returns the type name */ function getTypeName(type) { return type.name; } /** * Test whether a type is an exact type or conversion * @param {Type} type * @return {boolean} Returns true when */ function isExactType(type) { return type.conversion === null || type.conversion === undefined; } /** * 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 */ function mergeExpectedParams(signatures, index) { var typeNames = uniq(flatMap(signatures, function (signature) { return getExpectedTypeNames(signature, index, false); })); return (typeNames.indexOf('any') !== -1) ? ['any'] : typeNames; } /** * 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 `data` */ 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.filter(function (signature) { var test = compileTest(getParamAtIndex(signature, index)); return (index < signature.params.length || hasRestParam(signature.params)) && test(args[index]); }); if (nextMatchingDefs.length === 0) { // no matching signatures anymore, throw error "wrong type" expected = mergeExpectedParams(matchingSignatures, index); if (expected.length > 0) { var actualType = findTypeName(args[index]); err = new TypeError('Unexpected type of argument in function ' + _name + ' (expected: ' + expected.join(' or ') + ', actual: ' + actualType + ', index: ' + index + ')'); err.data = { category: 'wrongType', fn: _name, index: index, actual: actualType, expected: expected } return err; } } else { matchingSignatures = nextMatchingDefs; } } // test for too few arguments var lengths = matchingSignatures.map(function (signature) { return hasRestParam(signature.params) ? Infinity : signature.params.length; }); if (args.length < Math.min.apply(null, lengths)) { expected = mergeExpectedParams(matchingSignatures, index); err = new TypeError('Too few arguments in function ' + _name + ' (expected: ' + expected.join(' or ') + ', index: ' + args.length + ')'); err.data = { category: 'tooFewArgs', fn: _name, index: args.length, expected: expected } return err; } // test for too many arguments var maxLength = Math.max.apply(null, lengths); if (args.length > maxLength) { err = new TypeError('Too many arguments in function ' + _name + ' (expected: ' + maxLength + ', actual: ' + args.length + ')'); err.data = { category: 'tooManyArgs', fn: _name, index: args.length, expectedLength: maxLength } return err; } err = new TypeError('Arguments of type "' + args.join(', ') + '" do not match any of the defined signatures of function ' + _name + '.'); err.data = { category: 'mismatch', actual: args.map(findTypeName) } return err; } /** * 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 */ 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 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 */ 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; } /** * 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 */ 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) { return c; } // compare the index of the types c = getLowestTypeIndex(param1) - getLowestTypeIndex(param2); if (c !== 0) { return c; } // compare the index of any conversion return getLowestConversionIndex(param1) - getLowestConversionIndex(param2); } /** * 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 */ 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) if (c !== 0) { return c; } // next compare whether the params have conversions one by one for (i = 0; i < len; i++) { c = hasConversions(signature1.params[i]) - hasConversions(signature2.params[i]); if (c !== 0) { return c; } } // compare the types of the params one by one for (i = 0; i < len; i++) { c = compareParams(signature1.params[i], signature2.params[i]); if (c !== 0) { return c; } } // compare the number of params return signature1.params.length - signature2.params.length; } /** * 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) */ 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] = conversion; } }); return Object.keys(matches).map(function (from) { return matches[from]; }); } /** * 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 */ 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 = function convertArgs() { var args = []; var last = restParam ? arguments.length - 1 : arguments.length; for (var i = 0; i < last; i++) { args[i] = compiledConversions[i](arguments[i]); } if (restParam) { args[last] = arguments[last].map(compiledConversions[last]); } return fn.apply(null, args); } } var fnPreprocess = fnConvert; if (hasRestParam(params)) { var offset = params.length - 1; fnPreprocess = function preprocessRestParams () { return fnConvert.apply(null, slice(arguments, 0, offset).concat([slice(arguments, offset)])); } } return fnPreprocess; } /** * Compile conversion for a parameter to the right type * @param {Param} param * @return {function} Returns the wrapped function that will convert arguments * */ 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.conversion.convert); } }); // create optimized conversion functions depending on the number of conversions switch (conversions.length) { case 0: return function convertArg(arg) { return arg; } case 1: test0 = tests[0] conversion0 = conversions[0]; return function convertArg(arg) { if (test0(arg)) { return conversion0(arg) } return arg; } case 2: test0 = tests[0] test1 = tests[1] conversion0 = conversions[0]; conversion1 = conversions[1]; return function convertArg(arg) { if (test0(arg)) { return conversion0(arg) } if (test1(arg)) { return conversion1(arg) } return arg; } default: return function convertArg(arg) { for (var i = 0; i < conversions.length; i++) { if (tests[i](arg)) { return conversions[i](arg); } } return arg; } } } /** * 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 key and the original function * of this signature as value. */ 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; }); } }); return signaturesMap; } /** * 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 {boolean} ignoreConversionTypes * @return {Param[]} */ 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; var typeGroups if (param.restParam) { // split the types of a rest parameter in two: // one with only exact types, and one with exact types and conversions var exactTypes = filteredTypes.filter(isExactType) typeGroups = exactTypes.length < filteredTypes.length ? [exactTypes, filteredTypes] : [filteredTypes] } else { // split all the types of a regular parameter into one type per group typeGroups = filteredTypes.map(function (type) { return [type] }) } // recurse over the groups with types return flatMap(typeGroups, function (typeGroup) { return _splitParams(params, index + 1, types.concat([typeGroup])); }); } else { // we've reached the end of the parameters. Now build a new Param var splittedParams = types.map(function (type, typeIndex) { return { types: type, restParam: (typeIndex === params.length - 1) && hasRestParam(params) } }); return [splittedParams]; } } return _splitParams(params, 0, []); } /** * Test whether two signatures have a conflicting signature * @param {Signature} signature1 * @param {Signature} signature2 * @return {boolean} Returns true when the signatures conflict, false otherwise. */ 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 (!hasOverlap(typesNames1, typesNames2)) { return false; } } var len1 = signature1.params.length; var len2 = signature2.params.length; var restParam1 = hasRestParam(signature1.params); var restParam2 = hasRestParam(signature2.params); return restParam1 ? restParam2 ? (len1 === len2) : (len2 >= len1) : restParam2 ? (len1 >= len2) : (len1 === len2) } /** * 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 corresponding to the * signature as value. * @return {function} Returns the created typed function. */ 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 (signature) { return parseSignature(signature, signaturesMap[signature], typed.conversions); }) .filter(notNull) .forEach(function (parsedSignature) { // check whether this parameter conflicts with already parsed signatures var conflictingSignature = findInArray(parsedSignatures, function (s) { return hasConflictingParams(s, parsedSignature) }); if (conflictingSignature) { throw new TypeError('Conflicting signatures "' + stringifyParams(conflictingSignature.params) + '" and "' + stringifyParams(parsedSignature.params) + '".'); } parsedSignatures.push(parsedSignature); }); // split and filter the types of the signatures, and then order them var signatures = flatMap(parsedSignatures, function (parsedSignature) { var params = parsedSignature ? splitParams(parsedSignature.params, false) : [] return params.map(function (params) { return { params: params, fn: parsedSignature.fn }; }); }).filter(notNull); signatures.sort(compareSignatures); // we create a highly optimized checks for the first couple of signatures with max 2 arguments var ok0 = signatures[0] && signatures[0].params.length <= 2 && !hasRestParam(signatures[0].params); var ok1 = signatures[1] && signatures[1].params.length <= 2 && !hasRestParam(signatures[1].params); var ok2 = signatures[2] && signatures[2].params.length <= 2 && !hasRestParam(signatures[2].params); var ok3 = signatures[3] && signatures[3].params.length <= 2 && !hasRestParam(signatures[3].params); var ok4 = signatures[4] && signatures[4].params.length <= 2 && !hasRestParam(signatures[4].params); var ok5 = signatures[5] && signatures[5].params.length <= 2 && !hasRestParam(signatures[5].params); var allOk = ok0 && ok1 && ok2 && ok3 && ok4 && ok5; // compile the tests var tests = signatures.map(function (signature) { return compileTests(signature.params); }); var test00 = ok0 ? compileTest(signatures[0].params[0]) : notOk; var test10 = ok1 ? compileTest(signatures[1].params[0]) : notOk; var test20 = ok2 ? compileTest(signatures[2].params[0]) : notOk; var test30 = ok3 ? compileTest(signatures[3].params[0]) : notOk; var test40 = ok4 ? compileTest(signatures[4].params[0]) : notOk; var test50 = ok5 ? compileTest(signatures[5].params[0]) : notOk; var test01 = ok0 ? compileTest(signatures[0].params[1]) : notOk; var test11 = ok1 ? compileTest(signatures[1].params[1]) : notOk; var test21 = ok2 ? compileTest(signatures[2].params[1]) : notOk; var test31 = ok3 ? compileTest(signatures[3].params[1]) : notOk; var test41 = ok4 ? compileTest(signatures[4].params[1]) : notOk; var test51 = ok5 ? compileTest(signatures[5].params[1]) : notOk; // compile the functions var fns = signatures.map(function(signature) { return compileArgsPreprocessing(signature.params, signature.fn) }); var fn0 = ok0 ? fns[0] : undef; var fn1 = ok1 ? fns[1] : undef; var fn2 = ok2 ? fns[2] : undef; var fn3 = ok3 ? fns[3] : undef; var fn4 = ok4 ? fns[4] : undef; var fn5 = ok5 ? fns[5] : undef; var len0 = ok0 ? signatures[0].params.length : -1; var len1 = ok1 ? signatures[1].params.length : -1; var len2 = ok2 ? signatures[2].params.length : -1; var len3 = ok3 ? signatures[3].params.length : -1; var len4 = ok4 ? signatures[4].params.length : -1; var len5 = ok5 ? signatures[5].params.length : -1; // simple and generic, but also slow var iStart = allOk ? 6 : 0; var iEnd = signatures.length; var 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 the typed function // fast, specialized version. Falls back to the slower, generic one if needed var 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 && test20(arg0) && test21(arg1)) { return fn2.apply(null, arguments); } if (arguments.length === len3 && test30(arg0) && test31(arg1)) { return fn3.apply(null, arguments); } if (arguments.length === len4 && test40(arg0) && test41(arg1)) { return fn4.apply(null, arguments); } if (arguments.length === len5 && test50(arg0) && test51(arg1)) { return fn5.apply(null, arguments); } return generic.apply(null, arguments); } // attach name the typed function try { Object.defineProperty(fn, 'name', {value: name}); } catch (err) { // old browsers do not support Object.defineProperty and some don't support setting the name property // the function name is not essential for the functioning, it's mostly useful for debugging, // so it's fine to have unnamed functions. } // attach signatures to the function fn.signatures = createSignaturesMap(signatures); return fn; } /** * Test whether a type should be NOT be ignored * @param {string} typeName * @return {boolean} */ function notIgnore(typeName) { return typed.ignore.indexOf(typeName) === -1; } /** * trim a string * @param {string} str * @return {string} */ function trim(str) { return str.trim(); } /** * Test whether a string is not empty * @param {string} str * @return {boolean} */ function notEmpty(str) { return !!str; } /** * test whether a value is not strict equal to null * @param {*} value * @return {boolean} */ function notNull(value) { return value !== null; } /** * Test whether a parameter has no types defined * @param {Param} param * @return {boolean} */ function isInvalidParam (param) { return param.types.length === 0; } /** * Return all but the last items of an array * @param {Array} arr * @return {Array} */ function initial(arr) { return arr.slice(0, arr.length - 1); } /** * return the last item of an array * @param {Array} arr * @return {*} */ function last(arr) { return arr[arr.length - 1]; } /** * Slice an array or function Arguments * @param {Array | Arguments | IArguments} arr * @param {number} start * @param {number} [end] * @return {Array} */ function slice(arr, start, end) { return Array.prototype.slice.call(arr, start, end); } /** * Test whether an array contains some item * @param {Array} array * @param {*} item * @return {boolean} Returns true if array contains item, false if not. */ function contains(array, item) { return array.indexOf(item) !== -1; } /** * 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 */ function hasOverlap(array1, array2) { for (var i = 0; i < array1.length; i++) { if (contains(array2, array1[i])) { return true; } } return false; } /** * 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 */ function findInArray(arr, test) { for (var i = 0; i < arr.length; i++) { if (test(arr[i])) { return arr[i]; } } return undefined; } /** * Filter unique items of an array with strings * @param {string[]} arr * @return {string[]} */ function uniq(arr) { var entries = {} for (var i = 0; i < arr.length; i++) { entries[arr[i]] = true; } return Object.keys(entries); } /** * 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} */ function flatMap(arr, callback) { return Array.prototype.concat.apply([], arr.map(callback)); } /** * Retrieve the function name from a set of typed functions, * and check whether the name of all functions match (if given) * @param {function[]} fns */ 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 === '') { name = fn.name; } else if (name !== fn.name) { var err = new Error('Function names do not match (expected: ' + name + ', actual: ' + fn.name + ')'); err.data = { actual: fn.name, expected: name }; throw err; } } } return name; } // extract and merge all signatures of a list with typed functions 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 = {signature: _signature}; throw err; // else: both signatures point to the same function, that's fine } } for (var i = 0; i < fns.length; i++) { var fn = fns[i]; // test whether this is a typed-function if (typeof fn.signatures === 'object') { // merge the signatures for (var signature in fn.signatures) { if (fn.signatures.hasOwnProperty(signature)) { validateUnique(signature, fn.signatures[signature]); signaturesMap[signature] = fn.signatures[signature]; } } } else if (typeof fn.signature === 'string') { validateUnique(fn.signature, fn); signaturesMap[fn.signature] = fn; } else { err = new TypeError('Function is no typed-function (index: ' + i + ')'); err.data = {index: i}; throw err; } } return signaturesMap; } typed = createTypedFunction('typed', { 'string, Object': createTypedFunction, 'Object': function (signaturesMap) { // find existing name var fns = []; for (var signature in signaturesMap) { if (signaturesMap.hasOwnProperty(signature)) { fns.push(signaturesMap[signature]); } } var name = getName(fns); return createTypedFunction(name, signaturesMap); }, '...Function': function (fns) { return createTypedFunction(getName(fns), extractSignatures(fns)); }, 'string, ...Function': function (name, fns) { return createTypedFunction(name, extractSignatures(fns)); } }); typed.create = create; typed.types = _types; typed.conversions = _conversions; typed.ignore = _ignore; typed.convert = convert; typed.find = find; /** * add a type * @param {{name: string, test: function}} type * @param {boolean} [beforeObjectTest=true] * If true, the new test will be inserted before * the test with name 'Object' (if any), since * tests for Object match Array and classes too. */ typed.addType = function (type, beforeObjectTest) { if (!type || typeof type.name !== 'string' || typeof type.test !== 'function') { throw new TypeError('Object with properties {name: string, test: function} expected'); } if (beforeObjectTest !== false) { for (var i = 0; i < typed.types.length; i++) { if (typed.types[i].name === 'Object') { typed.types.splice(i, 0, type); return } } } typed.types.push(type); }; // add a conversion typed.addConversion = function (conversion) { if (!conversion || typeof conversion.from !== 'string' || typeof conversion.to !== 'string' || typeof conversion.convert !== 'function') { throw new TypeError('Object with properties {from: string, to: string, convert: function} expected'); } typed.conversions.push(conversion); }; return typed; }
@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 (*) : * }} ConversionDef @typedef {{ name: string, test: function(*) : boolean }} TypeDef
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 = findInArray(typed.types, function (entry) { return entry.name.toLowerCase() === typeName.toLowerCase(); }); throw new TypeError('Unknown type "' + typeName + '"' + (hint ? ('. Did you mean "' + hint.name + '"?') : '')); }
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[i].trim(); } } else if (Array.isArray(signature)) { arr = signature; } else { throw new TypeError('String array or a comma separated string expected'); } var str = arr.join(','); // find an exact match var match = fn.signatures[str]; if (match) { return match; } // TODO: extend find to match non-exact signatures throw new TypeError('Signature not found (signature: ' + (fn.name || 'unnamed') + '(' + arr.join(', ') + '))'); }
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 be an array or a comma separated string. @return {Function} Returns the matching signature, or throws an error when no signature is found.
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 && conversion.to === type) { return conversion.convert(value); } } throw new Error('Cannot convert from ' + from + ' to ' + type); }
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) .filter(notIgnore); var matchingConversions = filterConversions(conversions, typeNames); var exactTypes = typeNames.map(function (typeName) { var type = findTypeByName(typeName); return { name: typeName, typeIndex: findTypeIndex(type), test: type.test, conversion: null, conversionIndex: -1 }; }); var convertibleTypes = matchingConversions.map(function (conversion) { var type = findTypeByName(conversion.from); return { name: conversion.from, typeIndex: findTypeIndex(type), test: type.test, conversion: conversion, conversionIndex: conversions.indexOf(conversion) }; }); return { types: exactTypes.concat(convertibleTypes), restParam: restParam }; }
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); if (parsedParam.restParam && (index !== array.length - 1)) { throw new SyntaxError('Unexpected rest parameter "' + param + '": ' + 'only allowed for the last parameter'); } return parsedParam; }); } if (params.some(isInvalidParam)) { // invalid signature: at least one parameter has no types // (they may have been filtered) return null; } return { params: params, fn: fn }; }
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(param.types[0].name).test; var test1 = findTypeByName(param.types[1].name).test; return function or(x) { return test0(x) || test1(x); } } else { // param.types.length > 2 var tests = param.types.map(function (type) { return findTypeByName(type.name).test; }) return function or(x) { for (var i = 0; i < tests.length; i++) { if (tests[i](x)) { return true; } } return false; } } }
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 (args) { for (var i = varIndex; i < args.length; i++) { if (!lastTest(args[i])) { return false; } } return true; } return function testArgs(args) { for (var i = 0; i < tests.length; i++) { if (!tests[i](args[i])) { return false; } } return testRestParam(args) && (args.length >= varIndex + 1); }; } else { // no variable arguments if (params.length === 0) { return function testArgs(args) { return args.length === 0; }; } else if (params.length === 1) { test0 = compileTest(params[0]); return function testArgs(args) { return test0(args[0]) && args.length === 1; }; } else if (params.length === 2) { test0 = compileTest(params[0]); test1 = compileTest(params[1]); return function testArgs(args) { return test0(args[0]) && test1(args[1]) && args.length === 2; }; } else { // arguments.length > 2 tests = params.map(compileTest); return function testArgs(args) { for (var i = 0; i < tests.length; i++) { if (!tests[i](args[i])) { return false; } } return args.length === tests.length; }; } } }
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.filter(function (signature) { var test = compileTest(getParamAtIndex(signature, index)); return (index < signature.params.length || hasRestParam(signature.params)) && test(args[index]); }); if (nextMatchingDefs.length === 0) { // no matching signatures anymore, throw error "wrong type" expected = mergeExpectedParams(matchingSignatures, index); if (expected.length > 0) { var actualType = findTypeName(args[index]); err = new TypeError('Unexpected type of argument in function ' + _name + ' (expected: ' + expected.join(' or ') + ', actual: ' + actualType + ', index: ' + index + ')'); err.data = { category: 'wrongType', fn: _name, index: index, actual: actualType, expected: expected } return err; } } else { matchingSignatures = nextMatchingDefs; } } // test for too few arguments var lengths = matchingSignatures.map(function (signature) { return hasRestParam(signature.params) ? Infinity : signature.params.length; }); if (args.length < Math.min.apply(null, lengths)) { expected = mergeExpectedParams(matchingSignatures, index); err = new TypeError('Too few arguments in function ' + _name + ' (expected: ' + expected.join(' or ') + ', index: ' + args.length + ')'); err.data = { category: 'tooFewArgs', fn: _name, index: args.length, expected: expected } return err; } // test for too many arguments var maxLength = Math.max.apply(null, lengths); if (args.length > maxLength) { err = new TypeError('Too many arguments in function ' + _name + ' (expected: ' + maxLength + ', actual: ' + args.length + ')'); err.data = { category: 'tooManyArgs', fn: _name, index: args.length, expectedLength: maxLength } return err; } err = new TypeError('Arguments of type "' + args.join(', ') + '" do not match any of the defined signatures of function ' + _name + '.'); err.data = { category: 'mismatch', actual: args.map(findTypeName) } return err; }
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 `data`
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) { return c; } // compare the index of the types c = getLowestTypeIndex(param1) - getLowestTypeIndex(param2); if (c !== 0) { return c; } // compare the index of any conversion return getLowestConversionIndex(param1) - getLowestConversionIndex(param2); }
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) if (c !== 0) { return c; } // next compare whether the params have conversions one by one for (i = 0; i < len; i++) { c = hasConversions(signature1.params[i]) - hasConversions(signature2.params[i]); if (c !== 0) { return c; } } // compare the types of the params one by one for (i = 0; i < len; i++) { c = compareParams(signature1.params[i], signature2.params[i]); if (c !== 0) { return c; } } // compare the number of params return signature1.params.length - signature2.params.length; }
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] = conversion; } }); return Object.keys(matches).map(function (from) { return matches[from]; }); }
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 = function convertArgs() { var args = []; var last = restParam ? arguments.length - 1 : arguments.length; for (var i = 0; i < last; i++) { args[i] = compiledConversions[i](arguments[i]); } if (restParam) { args[last] = arguments[last].map(compiledConversions[last]); } return fn.apply(null, args); } } var fnPreprocess = fnConvert; if (hasRestParam(params)) { var offset = params.length - 1; fnPreprocess = function preprocessRestParams () { return fnConvert.apply(null, slice(arguments, 0, offset).concat([slice(arguments, offset)])); } } return fnPreprocess; }
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.conversion.convert); } }); // create optimized conversion functions depending on the number of conversions switch (conversions.length) { case 0: return function convertArg(arg) { return arg; } case 1: test0 = tests[0] conversion0 = conversions[0]; return function convertArg(arg) { if (test0(arg)) { return conversion0(arg) } return arg; } case 2: test0 = tests[0] test1 = tests[1] conversion0 = conversions[0]; conversion1 = conversions[1]; return function convertArg(arg) { if (test0(arg)) { return conversion0(arg) } if (test1(arg)) { return conversion1(arg) } return arg; } default: return function convertArg(arg) { for (var i = 0; i < conversions.length; i++) { if (tests[i](arg)) { return conversions[i](arg); } } return arg; } } }
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; }); } }); return signaturesMap; }
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 key and the original function of this signature as value.
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; var typeGroups if (param.restParam) { // split the types of a rest parameter in two: // one with only exact types, and one with exact types and conversions var exactTypes = filteredTypes.filter(isExactType) typeGroups = exactTypes.length < filteredTypes.length ? [exactTypes, filteredTypes] : [filteredTypes] } else { // split all the types of a regular parameter into one type per group typeGroups = filteredTypes.map(function (type) { return [type] }) } // recurse over the groups with types return flatMap(typeGroups, function (typeGroup) { return _splitParams(params, index + 1, types.concat([typeGroup])); }); } else { // we've reached the end of the parameters. Now build a new Param var splittedParams = types.map(function (type, typeIndex) { return { types: type, restParam: (typeIndex === params.length - 1) && hasRestParam(params) } }); return [splittedParams]; } } return _splitParams(params, 0, []); }
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 {boolean} ignoreConversionTypes @return {Param[]}
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 the types of a rest parameter in two: // one with only exact types, and one with exact types and conversions var exactTypes = filteredTypes.filter(isExactType) typeGroups = exactTypes.length < filteredTypes.length ? [exactTypes, filteredTypes] : [filteredTypes] } else { // split all the types of a regular parameter into one type per group typeGroups = filteredTypes.map(function (type) { return [type] }) } // recurse over the groups with types return flatMap(typeGroups, function (typeGroup) { return _splitParams(params, index + 1, types.concat([typeGroup])); }); } else { // we've reached the end of the parameters. Now build a new Param var splittedParams = types.map(function (type, typeIndex) { return { types: type, restParam: (typeIndex === params.length - 1) && hasRestParam(params) } }); return [splittedParams]; } }
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 {boolean} ignoreConversionTypes @return {Param[]}
_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 (!hasOverlap(typesNames1, typesNames2)) { return false; } } var len1 = signature1.params.length; var len2 = signature2.params.length; var restParam1 = hasRestParam(signature1.params); var restParam2 = hasRestParam(signature2.params); return restParam1 ? restParam2 ? (len1 === len2) : (len2 >= len1) : restParam2 ? (len1 >= len2) : (len1 === len2) }
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 (signature) { return parseSignature(signature, signaturesMap[signature], typed.conversions); }) .filter(notNull) .forEach(function (parsedSignature) { // check whether this parameter conflicts with already parsed signatures var conflictingSignature = findInArray(parsedSignatures, function (s) { return hasConflictingParams(s, parsedSignature) }); if (conflictingSignature) { throw new TypeError('Conflicting signatures "' + stringifyParams(conflictingSignature.params) + '" and "' + stringifyParams(parsedSignature.params) + '".'); } parsedSignatures.push(parsedSignature); }); // split and filter the types of the signatures, and then order them var signatures = flatMap(parsedSignatures, function (parsedSignature) { var params = parsedSignature ? splitParams(parsedSignature.params, false) : [] return params.map(function (params) { return { params: params, fn: parsedSignature.fn }; }); }).filter(notNull); signatures.sort(compareSignatures); // we create a highly optimized checks for the first couple of signatures with max 2 arguments var ok0 = signatures[0] && signatures[0].params.length <= 2 && !hasRestParam(signatures[0].params); var ok1 = signatures[1] && signatures[1].params.length <= 2 && !hasRestParam(signatures[1].params); var ok2 = signatures[2] && signatures[2].params.length <= 2 && !hasRestParam(signatures[2].params); var ok3 = signatures[3] && signatures[3].params.length <= 2 && !hasRestParam(signatures[3].params); var ok4 = signatures[4] && signatures[4].params.length <= 2 && !hasRestParam(signatures[4].params); var ok5 = signatures[5] && signatures[5].params.length <= 2 && !hasRestParam(signatures[5].params); var allOk = ok0 && ok1 && ok2 && ok3 && ok4 && ok5; // compile the tests var tests = signatures.map(function (signature) { return compileTests(signature.params); }); var test00 = ok0 ? compileTest(signatures[0].params[0]) : notOk; var test10 = ok1 ? compileTest(signatures[1].params[0]) : notOk; var test20 = ok2 ? compileTest(signatures[2].params[0]) : notOk; var test30 = ok3 ? compileTest(signatures[3].params[0]) : notOk; var test40 = ok4 ? compileTest(signatures[4].params[0]) : notOk; var test50 = ok5 ? compileTest(signatures[5].params[0]) : notOk; var test01 = ok0 ? compileTest(signatures[0].params[1]) : notOk; var test11 = ok1 ? compileTest(signatures[1].params[1]) : notOk; var test21 = ok2 ? compileTest(signatures[2].params[1]) : notOk; var test31 = ok3 ? compileTest(signatures[3].params[1]) : notOk; var test41 = ok4 ? compileTest(signatures[4].params[1]) : notOk; var test51 = ok5 ? compileTest(signatures[5].params[1]) : notOk; // compile the functions var fns = signatures.map(function(signature) { return compileArgsPreprocessing(signature.params, signature.fn) }); var fn0 = ok0 ? fns[0] : undef; var fn1 = ok1 ? fns[1] : undef; var fn2 = ok2 ? fns[2] : undef; var fn3 = ok3 ? fns[3] : undef; var fn4 = ok4 ? fns[4] : undef; var fn5 = ok5 ? fns[5] : undef; var len0 = ok0 ? signatures[0].params.length : -1; var len1 = ok1 ? signatures[1].params.length : -1; var len2 = ok2 ? signatures[2].params.length : -1; var len3 = ok3 ? signatures[3].params.length : -1; var len4 = ok4 ? signatures[4].params.length : -1; var len5 = ok5 ? signatures[5].params.length : -1; // simple and generic, but also slow var iStart = allOk ? 6 : 0; var iEnd = signatures.length; var 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 the typed function // fast, specialized version. Falls back to the slower, generic one if needed var 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 && test20(arg0) && test21(arg1)) { return fn2.apply(null, arguments); } if (arguments.length === len3 && test30(arg0) && test31(arg1)) { return fn3.apply(null, arguments); } if (arguments.length === len4 && test40(arg0) && test41(arg1)) { return fn4.apply(null, arguments); } if (arguments.length === len5 && test50(arg0) && test51(arg1)) { return fn5.apply(null, arguments); } return generic.apply(null, arguments); } // attach name the typed function try { Object.defineProperty(fn, 'name', {value: name}); } catch (err) { // old browsers do not support Object.defineProperty and some don't support setting the name property // the function name is not essential for the functioning, it's mostly useful for debugging, // so it's fine to have unnamed functions. } // attach signatures to the function fn.signatures = createSignaturesMap(signatures); return fn; }
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 corresponding to the signature as value. @return {function} Returns the created typed function.
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 corresponding to the signature as value. @return {function} Returns the created typed function.
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 && test20(arg0) && test21(arg1)) { return fn2.apply(null, arguments); } if (arguments.length === len3 && test30(arg0) && test31(arg1)) { return fn3.apply(null, arguments); } if (arguments.length === len4 && test40(arg0) && test41(arg1)) { return fn4.apply(null, arguments); } if (arguments.length === len5 && test50(arg0) && test51(arg1)) { return fn5.apply(null, arguments); } return generic.apply(null, arguments); }
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 corresponding to the signature as value. @return {function} Returns the created typed function.
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 === '') { name = fn.name; } else if (name !== fn.name) { var err = new Error('Function names do not match (expected: ' + name + ', actual: ' + fn.name + ')'); err.data = { actual: fn.name, expected: name }; throw err; } } } return 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 = {signature: _signature}; throw err; // else: both signatures point to the same function, that's fine } } for (var i = 0; i < fns.length; i++) { var fn = fns[i]; // test whether this is a typed-function if (typeof fn.signatures === 'object') { // merge the signatures for (var signature in fn.signatures) { if (fn.signatures.hasOwnProperty(signature)) { validateUnique(signature, fn.signatures[signature]); signaturesMap[signature] = fn.signatures[signature]; } } } else if (typeof fn.signature === 'string') { validateUnique(fn.signature, fn); signaturesMap[fn.signature] = fn; } else { err = new TypeError('Function is no typed-function (index: ' + i + ')'); err.data = {index: i}; throw err; } } return signaturesMap; }
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 point to the same function, that's fine } }
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