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 _nthComplexRoots(a, root) { if (root < 0) throw new Error('Root must be greater than zero'); if (root === 0) throw new Error('Root must be non-zero'); if (root % 1 !== 0) throw new Error('Root must be an integer'); if (a === 0 || a.abs() === 0) return [complex(0)]; var aIsNumeric = typeof a === 'number'; var offset; // determine the offset (argument of a)/(pi/2) if (aIsNumeric || a.re === 0 || a.im === 0) { if (aIsNumeric) { offset = 2 * +(a < 0); // numeric value on the real axis } else if (a.im === 0) { offset = 2 * +(a.re < 0); // complex value on the real axis } else { offset = 2 * +(a.im < 0) + 1; // complex value on the imaginary axis } } var arg = a.arg(); var abs = a.abs(); var roots = []; var r = Math.pow(abs, 1 / root); for (var k = 0; k < root; k++) { var halfPiFactor = (offset + 4 * k) / root; /** * If (offset + 4*k)/root is an integral multiple of pi/2 * then we can produce a more exact result. */ if (halfPiFactor === Math.round(halfPiFactor)) { roots.push(_calculateExactResult[halfPiFactor % 4](r)); continue; } roots.push(complex({ r: r, phi: (arg + 2 * Math.PI * k) / root })); } return roots; }
Calculate the nth root of a Complex Number a using De Movire's Theorem. @param {Complex} a @param {number} root @return {Array} array of n Complex Roots
_nthComplexRoots
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _xgcd(a, b) { // source: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm var t; // used to swap two variables var q; // quotient var r; // remainder var x = 0; var lastx = 1; var y = 1; var lasty = 0; if (!isInteger(a) || !isInteger(b)) { throw new Error('Parameters in function xgcd must be integer numbers'); } while (b) { q = Math.floor(a / b); r = a - q * b; t = x; x = lastx - q * x; lastx = t; t = y; y = lasty - q * y; lasty = t; a = b; b = r; } var res; if (a < 0) { res = [-a, -lastx, -lasty]; } else { res = [a, a ? lastx : 0, lasty]; } return config.matrix === 'Array' ? res : matrix(res); }
Calculate xgcd for two numbers @param {number} a @param {number} b @return {number} result @private
_xgcd
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _xgcdBigNumber(a, b) { // source: https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm var // used to swap two variables t; var // quotient q; var // remainder r; var zero = new type.BigNumber(0); var one = new type.BigNumber(1); var x = zero; var lastx = one; var y = one; var lasty = zero; if (!a.isInt() || !b.isInt()) { throw new Error('Parameters in function xgcd must be integer numbers'); } while (!b.isZero()) { q = a.div(b).floor(); r = a.mod(b); t = x; x = lastx.minus(q.times(x)); lastx = t; t = y; y = lasty.minus(q.times(y)); lasty = t; a = b; b = r; } var res; if (a.lt(zero)) { res = [a.neg(), lastx.neg(), lasty.neg()]; } else { res = [a, !a.isZero() ? lastx : 0, lasty]; } return config.matrix === 'Array' ? res : matrix(res); }
Calculate xgcd for two BigNumbers @param {BigNumber} a @param {BigNumber} b @return {BigNumber[]} result @private
_xgcdBigNumber
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _isNumber(a) { // intersect supports numbers and bignumbers return typeof a === 'number' || type.isBigNumber(a); }
Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in three dimensions. The inputs are in the form of arrays or 1 dimensional matrices. The line intersection functions return null if the lines do not meet. Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`. Syntax: math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2) math.intersect(endPoint1, endPoint2, planeCoefficients) Examples: math.intersect([0, 0], [10, 10], [10, 0], [0, 10]) // Returns [5, 5] math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]) // Returns [5, 5, 0] math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]) // Returns [7, -4, 3] @param {Array | Matrix} w Co-ordinates of first end-point of first line @param {Array | Matrix} x Co-ordinates of second end-point of first line @param {Array | Matrix} y Co-ordinates of first end-point of second line OR Co-efficients of the plane's equation @param {Array | Matrix} z Co-ordinates of second end-point of second line OR null if the calculation is for line and plane @return {Array} Returns the point of intersection of lines/lines-planes
_isNumber
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _2d(x) { return x.length === 2 && _isNumber(x[0]) && _isNumber(x[1]); }
Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in three dimensions. The inputs are in the form of arrays or 1 dimensional matrices. The line intersection functions return null if the lines do not meet. Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`. Syntax: math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2) math.intersect(endPoint1, endPoint2, planeCoefficients) Examples: math.intersect([0, 0], [10, 10], [10, 0], [0, 10]) // Returns [5, 5] math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]) // Returns [5, 5, 0] math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]) // Returns [7, -4, 3] @param {Array | Matrix} w Co-ordinates of first end-point of first line @param {Array | Matrix} x Co-ordinates of second end-point of first line @param {Array | Matrix} y Co-ordinates of first end-point of second line OR Co-efficients of the plane's equation @param {Array | Matrix} z Co-ordinates of second end-point of second line OR null if the calculation is for line and plane @return {Array} Returns the point of intersection of lines/lines-planes
_2d
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _3d(x) { return x.length === 3 && _isNumber(x[0]) && _isNumber(x[1]) && _isNumber(x[2]); }
Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in three dimensions. The inputs are in the form of arrays or 1 dimensional matrices. The line intersection functions return null if the lines do not meet. Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`. Syntax: math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2) math.intersect(endPoint1, endPoint2, planeCoefficients) Examples: math.intersect([0, 0], [10, 10], [10, 0], [0, 10]) // Returns [5, 5] math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]) // Returns [5, 5, 0] math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]) // Returns [7, -4, 3] @param {Array | Matrix} w Co-ordinates of first end-point of first line @param {Array | Matrix} x Co-ordinates of second end-point of first line @param {Array | Matrix} y Co-ordinates of first end-point of second line OR Co-efficients of the plane's equation @param {Array | Matrix} z Co-ordinates of second end-point of second line OR null if the calculation is for line and plane @return {Array} Returns the point of intersection of lines/lines-planes
_3d
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _4d(x) { return x.length === 4 && _isNumber(x[0]) && _isNumber(x[1]) && _isNumber(x[2]) && _isNumber(x[3]); }
Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in three dimensions. The inputs are in the form of arrays or 1 dimensional matrices. The line intersection functions return null if the lines do not meet. Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`. Syntax: math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2) math.intersect(endPoint1, endPoint2, planeCoefficients) Examples: math.intersect([0, 0], [10, 10], [10, 0], [0, 10]) // Returns [5, 5] math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]) // Returns [5, 5, 0] math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]) // Returns [7, -4, 3] @param {Array | Matrix} w Co-ordinates of first end-point of first line @param {Array | Matrix} x Co-ordinates of second end-point of first line @param {Array | Matrix} y Co-ordinates of first end-point of second line OR Co-efficients of the plane's equation @param {Array | Matrix} z Co-ordinates of second end-point of second line OR null if the calculation is for line and plane @return {Array} Returns the point of intersection of lines/lines-planes
_4d
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _intersect2d(p1a, p1b, p2a, p2b) { var o1 = p1a; var o2 = p2a; var d1 = subtract(o1, p1b); var d2 = subtract(o2, p2b); var det = subtract(multiplyScalar(d1[0], d2[1]), multiplyScalar(d2[0], d1[1])); if (smaller(abs(det), config.epsilon)) { return null; } var d20o11 = multiplyScalar(d2[0], o1[1]); var d21o10 = multiplyScalar(d2[1], o1[0]); var d20o21 = multiplyScalar(d2[0], o2[1]); var d21o20 = multiplyScalar(d2[1], o2[0]); var t = divideScalar(addScalar(subtract(subtract(d20o11, d21o10), d20o21), d21o20), det); return add(multiply(d1, t), o1); }
Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in three dimensions. The inputs are in the form of arrays or 1 dimensional matrices. The line intersection functions return null if the lines do not meet. Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`. Syntax: math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2) math.intersect(endPoint1, endPoint2, planeCoefficients) Examples: math.intersect([0, 0], [10, 10], [10, 0], [0, 10]) // Returns [5, 5] math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]) // Returns [5, 5, 0] math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]) // Returns [7, -4, 3] @param {Array | Matrix} w Co-ordinates of first end-point of first line @param {Array | Matrix} x Co-ordinates of second end-point of first line @param {Array | Matrix} y Co-ordinates of first end-point of second line OR Co-efficients of the plane's equation @param {Array | Matrix} z Co-ordinates of second end-point of second line OR null if the calculation is for line and plane @return {Array} Returns the point of intersection of lines/lines-planes
_intersect2d
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _intersect3dHelper(a, b, c, d, e, f, g, h, i, j, k, l) { // (a - b)*(c - d) + (e - f)*(g - h) + (i - j)*(k - l) var add1 = multiplyScalar(subtract(a, b), subtract(c, d)); var add2 = multiplyScalar(subtract(e, f), subtract(g, h)); var add3 = multiplyScalar(subtract(i, j), subtract(k, l)); return addScalar(addScalar(add1, add2), add3); }
Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in three dimensions. The inputs are in the form of arrays or 1 dimensional matrices. The line intersection functions return null if the lines do not meet. Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`. Syntax: math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2) math.intersect(endPoint1, endPoint2, planeCoefficients) Examples: math.intersect([0, 0], [10, 10], [10, 0], [0, 10]) // Returns [5, 5] math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]) // Returns [5, 5, 0] math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]) // Returns [7, -4, 3] @param {Array | Matrix} w Co-ordinates of first end-point of first line @param {Array | Matrix} x Co-ordinates of second end-point of first line @param {Array | Matrix} y Co-ordinates of first end-point of second line OR Co-efficients of the plane's equation @param {Array | Matrix} z Co-ordinates of second end-point of second line OR null if the calculation is for line and plane @return {Array} Returns the point of intersection of lines/lines-planes
_intersect3dHelper
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _intersect3d(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) { var d1343 = _intersect3dHelper(x1, x3, x4, x3, y1, y3, y4, y3, z1, z3, z4, z3); var d4321 = _intersect3dHelper(x4, x3, x2, x1, y4, y3, y2, y1, z4, z3, z2, z1); var d1321 = _intersect3dHelper(x1, x3, x2, x1, y1, y3, y2, y1, z1, z3, z2, z1); var d4343 = _intersect3dHelper(x4, x3, x4, x3, y4, y3, y4, y3, z4, z3, z4, z3); var d2121 = _intersect3dHelper(x2, x1, x2, x1, y2, y1, y2, y1, z2, z1, z2, z1); var ta = divideScalar(subtract(multiplyScalar(d1343, d4321), multiplyScalar(d1321, d4343)), subtract(multiplyScalar(d2121, d4343), multiplyScalar(d4321, d4321))); var tb = divideScalar(addScalar(d1343, multiplyScalar(ta, d4321)), d4343); var pax = addScalar(x1, multiplyScalar(ta, subtract(x2, x1))); var pay = addScalar(y1, multiplyScalar(ta, subtract(y2, y1))); var paz = addScalar(z1, multiplyScalar(ta, subtract(z2, z1))); var pbx = addScalar(x3, multiplyScalar(tb, subtract(x4, x3))); var pby = addScalar(y3, multiplyScalar(tb, subtract(y4, y3))); var pbz = addScalar(z3, multiplyScalar(tb, subtract(z4, z3))); if (equalScalar(pax, pbx) && equalScalar(pay, pby) && equalScalar(paz, pbz)) { return [pax, pay, paz]; } else { return null; } }
Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in three dimensions. The inputs are in the form of arrays or 1 dimensional matrices. The line intersection functions return null if the lines do not meet. Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`. Syntax: math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2) math.intersect(endPoint1, endPoint2, planeCoefficients) Examples: math.intersect([0, 0], [10, 10], [10, 0], [0, 10]) // Returns [5, 5] math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]) // Returns [5, 5, 0] math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]) // Returns [7, -4, 3] @param {Array | Matrix} w Co-ordinates of first end-point of first line @param {Array | Matrix} x Co-ordinates of second end-point of first line @param {Array | Matrix} y Co-ordinates of first end-point of second line OR Co-efficients of the plane's equation @param {Array | Matrix} z Co-ordinates of second end-point of second line OR null if the calculation is for line and plane @return {Array} Returns the point of intersection of lines/lines-planes
_intersect3d
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _intersectLinePlane(x1, y1, z1, x2, y2, z2, x, y, z, c) { var x1x = multiplyScalar(x1, x); var x2x = multiplyScalar(x2, x); var y1y = multiplyScalar(y1, y); var y2y = multiplyScalar(y2, y); var z1z = multiplyScalar(z1, z); var z2z = multiplyScalar(z2, z); var t = divideScalar(subtract(subtract(subtract(c, x1x), y1y), z1z), subtract(subtract(subtract(addScalar(addScalar(x2x, y2y), z2z), x1x), y1y), z1z)); var px = addScalar(x1, multiplyScalar(t, subtract(x2, x1))); var py = addScalar(y1, multiplyScalar(t, subtract(y2, y1))); var pz = addScalar(z1, multiplyScalar(t, subtract(z2, z1))); return [px, py, pz]; // TODO: Add cases when line is parallel to the plane: // (a) no intersection, // (b) line contained in plane }
Calculates the point of intersection of two lines in two or three dimensions and of a line and a plane in three dimensions. The inputs are in the form of arrays or 1 dimensional matrices. The line intersection functions return null if the lines do not meet. Note: Fill the plane coefficients as `x + y + z = c` and not as `x + y + z + c = 0`. Syntax: math.intersect(endPoint1Line1, endPoint2Line1, endPoint1Line2, endPoint2Line2) math.intersect(endPoint1, endPoint2, planeCoefficients) Examples: math.intersect([0, 0], [10, 10], [10, 0], [0, 10]) // Returns [5, 5] math.intersect([0, 0, 0], [10, 10, 0], [10, 0, 0], [0, 10, 0]) // Returns [5, 5, 0] math.intersect([1, 0, 1], [4, -2, 2], [1, 1, 1, 6]) // Returns [7, -4, 3] @param {Array | Matrix} w Co-ordinates of first end-point of first line @param {Array | Matrix} x Co-ordinates of second end-point of first line @param {Array | Matrix} y Co-ordinates of first end-point of second line OR Co-efficients of the plane's equation @param {Array | Matrix} z Co-ordinates of second end-point of second line OR null if the calculation is for line and plane @return {Array} Returns the point of intersection of lines/lines-planes
_intersectLinePlane
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _cross(x, y) { var highestDimension = Math.max(array.size(x).length, array.size(y).length); x = array.squeeze(x); y = array.squeeze(y); var xSize = array.size(x); var ySize = array.size(y); if (xSize.length !== 1 || ySize.length !== 1 || xSize[0] !== 3 || ySize[0] !== 3) { throw new RangeError('Vectors with length 3 expected ' + '(Size A = [' + xSize.join(', ') + '], B = [' + ySize.join(', ') + '])'); } var product = [subtract(multiply(x[1], y[2]), multiply(x[2], y[1])), subtract(multiply(x[2], y[0]), multiply(x[0], y[2])), subtract(multiply(x[0], y[1]), multiply(x[1], y[0]))]; if (highestDimension > 1) { return [product]; } else { return product; } }
Calculate the cross product for two arrays @param {Array} x First vector @param {Array} y Second vector @returns {Array} Returns the cross product of x and y @private
_cross
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _diag(x, k, size, format) { if (!isInteger(k)) { throw new TypeError('Second parameter in function diag must be an integer'); } var kSuper = k > 0 ? k : 0; var kSub = k < 0 ? -k : 0; // check dimensions switch (size.length) { case 1: return _createDiagonalMatrix(x, k, format, size[0], kSub, kSuper); case 2: return _getDiagonal(x, k, format, size, kSub, kSuper); } throw new RangeError('Matrix for function diag must be 2 dimensional'); }
Creeate diagonal matrix from a vector or vice versa @param {Array | Matrix} x @param {number} k @param {string} format Storage format for matrix. If null, an Array is returned @returns {Array | Matrix} @private
_diag
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _createDiagonalMatrix(x, k, format, l, kSub, kSuper) { // matrix size var ms = [l + kSub, l + kSuper]; // get matrix constructor var F = type.Matrix.storage(format || 'dense'); // create diagonal matrix var m = F.diagonal(ms, x, k); // check we need to return a matrix return format !== null ? m : m.valueOf(); }
Creeate diagonal matrix from a vector or vice versa @param {Array | Matrix} x @param {number} k @param {string} format Storage format for matrix. If null, an Array is returned @returns {Array | Matrix} @private
_createDiagonalMatrix
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _getDiagonal(x, k, format, s, kSub, kSuper) { // check x is a Matrix if (type.isMatrix(x)) { // get diagonal matrix var dm = x.diagonal(k); // check we need to return a matrix if (format !== null) { // check we need to change matrix format if (format !== dm.storage()) { return matrix(dm, format); } return dm; } return dm.valueOf(); } // vector size var n = Math.min(s[0] - kSub, s[1] - kSuper); // diagonal values var vector = []; // loop diagonal for (var i = 0; i < n; i++) { vector[i] = x[i + kSub][i + kSuper]; } // check we need to return a matrix return format !== null ? matrix(vector) : vector; }
Creeate diagonal matrix from a vector or vice versa @param {Array | Matrix} x @param {number} k @param {string} format Storage format for matrix. If null, an Array is returned @returns {Array | Matrix} @private
_getDiagonal
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _dot(x, y) { var xSize = size(x); var ySize = size(y); var len = xSize[0]; if (xSize.length !== 1 || ySize.length !== 1) throw new RangeError('Vector expected'); // TODO: better error message if (xSize[0] !== ySize[0]) throw new RangeError('Vectors must have equal length (' + xSize[0] + ' != ' + ySize[0] + ')'); if (len === 0) throw new RangeError('Cannot calculate the dot product of empty vectors'); var prod = 0; for (var i = 0; i < len; i++) { prod = add(prod, multiply(x[i], y[i])); } return prod; }
Calculate the dot product for two arrays @param {Array} x First vector @param {Array} y Second vector @returns {number} Returns the dot product of x and y @private
_dot
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function findParams(infNorm, eps) { var maxSearchSize = 30; for (var k = 0; k < maxSearchSize; k++) { for (var q = 0; q <= k; q++) { var j = k - q; if (errorEstimate(infNorm, q, j) < eps) { return { q: q, j: j }; } } } throw new Error('Could not find acceptable parameters to compute the matrix exponential (try increasing maxSearchSize in expm.js)'); }
Find the best parameters for the Pade approximant given the matrix norm and desired accuracy. Returns the first acceptable combination in order of increasing computational load.
findParams
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function errorEstimate(infNorm, q, j) { var qfac = 1; for (var i = 2; i <= q; i++) { qfac *= i; } var twoqfac = qfac; for (var _i2 = q + 1; _i2 <= 2 * q; _i2++) { twoqfac *= _i2; } var twoqp1fac = twoqfac * (2 * q + 1); return 8.0 * Math.pow(infNorm / Math.pow(2, j), 2 * q) * qfac * qfac / (twoqfac * twoqp1fac); }
Returns the estimated error of the Pade approximant for the given parameters.
errorEstimate
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _filterCallback(x, callback) { // figure out what number of arguments the callback function expects var args = maxArgumentCount(callback); return filter(x, function (value, index, array) { // 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); } }); }
Filter values in a callback given a callback function @param {Array} x @param {Function} callback @return {Array} Returns the filtered array @private
_filterCallback
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _forEach(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)) { forEach(value, function (child, i) { // we create a copy of the index array and append the new index value recurse(child, index.concat(i)); }); } else { // invoke the callback function with the right number of arguments if (args === 1) { callback(value); } else if (args === 2) { callback(value, index); } else { // 3 or -1 callback(value, index, array); } } }; recurse(array, []); }
forEach for a multi dimensional array @param {Array} array @param {Function} callback @private
_forEach
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
recurse = function recurse(value, index) { if (Array.isArray(value)) { forEach(value, function (child, i) { // we create a copy of the index array and append the new index value recurse(child, index.concat(i)); }); } else { // invoke the callback function with the right number of arguments if (args === 1) { callback(value); } else if (args === 2) { callback(value, index); } else { // 3 or -1 callback(value, index, array); } } }
forEach for a multi dimensional array @param {Array} array @param {Function} callback @private
recurse
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _kron(a, b) { // Deal with the dimensions of the matricies. if (size(a).length === 1) { // Wrap it in a 2D Matrix a = [a]; } if (size(b).length === 1) { // Wrap it in a 2D Matrix b = [b]; } if (size(a).length > 2 || size(b).length > 2) { throw new RangeError('Vectors with dimensions greater then 2 are not supported expected ' + '(Size x = ' + JSON.stringify(a.length) + ', y = ' + JSON.stringify(b.length) + ')'); } var t = []; var r = []; return a.map(function (a) { return b.map(function (b) { r = []; t.push(r); return a.map(function (y) { return b.map(function (x) { return r.push(multiplyScalar(y, x)); }); }); }); }) && t; }
Calculate the kronecker product of two matrices / vectors @param {Array} a First vector @param {Array} b Second vector @returns {Array} Returns the kronecker product of x and y @private
_kron
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _ones(size, format) { var hasBigNumbers = _normalize(size); var defaultValue = hasBigNumbers ? new type.BigNumber(1) : 1; _validate(size); if (format) { // return a matrix var m = matrix(format); if (size.length > 0) { return m.resize(size, defaultValue); } return m; } else { // return an Array var arr = []; if (size.length > 0) { return resize(arr, size, defaultValue); } return arr; } } // replace BigNumbers with numbers, returns true if size contained BigNumbers
Create an Array or Matrix with ones @param {Array} size @param {string} [format='default'] @return {Array | Matrix} @private
_ones
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _normalize(size) { var hasBigNumbers = false; size.forEach(function (value, index, arr) { if (type.isBigNumber(value)) { hasBigNumbers = true; arr[index] = value.toNumber(); } }); return hasBigNumbers; } // validate arguments
Create an Array or Matrix with ones @param {Array} size @param {string} [format='default'] @return {Array | Matrix} @private
_normalize
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _validate(size) { size.forEach(function (value) { if (typeof value !== 'number' || !isInteger(value) || value < 0) { throw new Error('Parameters in function ones must be positive integers'); } }); }
Create an Array or Matrix with ones @param {Array} size @param {string} [format='default'] @return {Array | Matrix} @private
_validate
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
resize = function resize(x, size, defaultValue) { if (arguments.length !== 2 && arguments.length !== 3) { throw new ArgumentsError('resize', arguments.length, 2, 3); } if (type.isMatrix(size)) { size = size.valueOf(); // get Array } if (type.isBigNumber(size[0])) { // convert bignumbers to numbers size = size.map(function (value) { return type.isBigNumber(value) ? value.toNumber() : value; }); } // check x is a Matrix if (type.isMatrix(x)) { // use optimized matrix implementation, return copy return x.resize(size, defaultValue, true); } if (typeof x === 'string') { // resize string return _resizeString(x, size, defaultValue); } // check result should be a matrix var asMatrix = Array.isArray(x) ? false : config.matrix !== 'Array'; if (size.length === 0) { // output a scalar while (Array.isArray(x)) { x = x[0]; } return clone(x); } else { // output an array/matrix if (!Array.isArray(x)) { x = [x]; } x = clone(x); var res = array.resize(x, size, defaultValue); return asMatrix ? matrix(res) : res; } }
Resize a matrix Syntax: math.resize(x, size) math.resize(x, size, defaultValue) Examples: math.resize([1, 2, 3, 4, 5], [3]) // returns Array [1, 2, 3] math.resize([1, 2, 3], [5], 0) // returns Array [1, 2, 3, 0, 0] math.resize(2, [2, 3], 0) // returns Matrix [[2, 0, 0], [0, 0, 0]] math.resize("hello", [8], "!") // returns string 'hello!!!' See also: size, squeeze, subset, reshape @param {Array | Matrix | *} x Matrix to be resized @param {Array | Matrix} size One dimensional array with numbers @param {number | string} [defaultValue=0] Zero by default, except in case of a string, in that case defaultValue = ' ' @return {* | Array | Matrix} A resized clone of matrix `x`
resize
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _resizeString(str, size, defaultChar) { if (defaultChar !== undefined) { if (typeof defaultChar !== 'string' || defaultChar.length !== 1) { throw new TypeError('Single character expected as defaultValue'); } } else { defaultChar = ' '; } if (size.length !== 1) { throw new DimensionError(size.length, 1); } var len = size[0]; if (typeof len !== 'number' || !isInteger(len)) { throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + format(size) + ')'); } if (str.length > len) { return str.substring(0, len); } else if (str.length < len) { var res = str; for (var i = 0, ii = len - str.length; i < ii; i++) { res += defaultChar; } return res; } else { return str; } }
Resize a string @param {string} str @param {number[]} size @param {string} [defaultChar=' '] @private
_resizeString
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _comparator(order) { if (order === 'asc') { return compareAsc; } else if (order === 'desc') { return compareDesc; } else if (order === 'natural') { return compareNatural; } else { throw new Error('String "asc", "desc", or "natural" expected'); } }
Get the comparator for given order ('asc', 'desc', 'natural') @param {'asc' | 'desc' | 'natural'} order @return {Function} Returns a _comparator function
_comparator
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _arrayIsVector(array) { if (size(array).length !== 1) { throw new Error('One dimensional array expected'); } }
Validate whether an array is one dimensional Throws an error when this is not the case @param {Array} array @private
_arrayIsVector
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _matrixIsVector(matrix) { if (matrix.size().length !== 1) { throw new Error('One dimensional matrix expected'); } }
Validate whether a matrix is one dimensional Throws an error when this is not the case @param {Matrix} matrix @private
_matrixIsVector
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _denseTrace(m) { // matrix size & data var size = m._size; var data = m._data; // process dimensions switch (size.length) { case 1: // vector if (size[0] === 1) { // return data[0] return clone(data[0]); } throw new RangeError('Matrix must be square (size: ' + format(size) + ')'); case 2: // two dimensional var rows = size[0]; var cols = size[1]; if (rows === cols) { // calulate sum var sum = 0; // loop diagonal for (var i = 0; i < rows; i++) { sum = add(sum, data[i][i]); } // return trace return sum; } throw new RangeError('Matrix must be square (size: ' + format(size) + ')'); default: // multi dimensional throw new RangeError('Matrix must be two dimensional (size: ' + format(size) + ')'); } }
Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix. Syntax: math.trace(x) Examples: math.trace([[1, 2], [3, 4]]) // returns 5 const A = [ [1, 2, 3], [-1, 2, 3], [2, 0, 3] ] math.trace(A) // returns 6 See also: diag @param {Array | Matrix} x A matrix @return {number} The trace of `x`
_denseTrace
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _sparseTrace(m) { // matrix arrays var values = m._values; var index = m._index; var ptr = m._ptr; var size = m._size; // check dimensions var rows = size[0]; var columns = size[1]; // matrix must be square if (rows === columns) { // calulate sum var sum = 0; // check we have data (avoid looping columns) if (values.length > 0) { // loop columns for (var j = 0; j < columns; j++) { // k0 <= k < k1 where k0 = _ptr[j] && k1 = _ptr[j+1] var k0 = ptr[j]; var k1 = ptr[j + 1]; // loop k within [k0, k1[ for (var k = k0; k < k1; k++) { // row index var i = index[k]; // check row if (i === j) { // accumulate value sum = add(sum, values[k]); // exit loop break; } if (i > j) { // exit loop, no value on the diagonal for column j break; } } } } // return trace return sum; } throw new RangeError('Matrix must be square (size: ' + format(size) + ')'); }
Calculate the trace of a matrix: the sum of the elements on the main diagonal of a square matrix. Syntax: math.trace(x) Examples: math.trace([[1, 2], [3, 4]]) // returns 5 const A = [ [1, 2, 3], [-1, 2, 3], [2, 0, 3] ] math.trace(A) // returns 6 See also: diag @param {Array | Matrix} x A matrix @return {number} The trace of `x`
_sparseTrace
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _kldiv(q, p) { var plength = p.size().length; var qlength = q.size().length; if (plength > 1) { throw new Error('first object must be one dimensional'); } if (qlength > 1) { throw new Error('second object must be one dimensional'); } if (plength !== qlength) { throw new Error('Length of two vectors must be equal'); } // Before calculation, apply normalization var sumq = sum(q); if (sumq === 0) { throw new Error('Sum of elements in first object must be non zero'); } var sump = sum(p); if (sump === 0) { throw new Error('Sum of elements in second object must be non zero'); } var qnorm = divide(q, sum(q)); var pnorm = divide(p, sum(p)); var result = sum(multiply(qnorm, log(dotDivide(qnorm, pnorm)))); if (isNumeric(result)) { return result; } else { return Number.NaN; } }
Calculate the Kullback-Leibler (KL) divergence between two distributions Syntax: math.kldivergence(x, y) Examples: math.kldivergence([0.7,0.5,0.4], [0.2,0.9,0.5]) //returns 0.24376698773121153 @param {Array | Matrix} q First vector @param {Array | Matrix} p Second vector @return {number} Returns distance between q and p
_kldiv
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _deepEqual(x, y) { if (Array.isArray(x)) { if (Array.isArray(y)) { var len = x.length; if (len !== y.length) { return false; } for (var i = 0; i < len; i++) { if (!_deepEqual(x[i], y[i])) { return false; } } return true; } else { return false; } } else { if (Array.isArray(y)) { return false; } else { return equal(x, y); } } }
Test whether two arrays have the same size and all elements are equal @param {Array | *} x @param {Array | *} y @return {boolean} Returns true if both arrays are deep equal
_deepEqual
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _subset(array, bitarray) { var result = []; for (var i = 0; i < bitarray.length; i++) { if (bitarray[i] === '1') { result.push(array[i]); } } return result; } // sort subsests by length
Create the powerset of a (multi)set. (The powerset contains very possible subsets of a (multi)set.) A multi-dimension array will be converted to a single-dimension array before the operation. Syntax: math.setPowerset(set) Examples: math.setPowerset([1, 2, 3]) // returns [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] See also: setCartesian @param {Array | Matrix} a A (multi)set @return {Array} The powerset of the (multi)set
_subset
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _sort(array) { var temp = []; for (var i = array.length - 1; i > 0; i--) { for (var j = 0; j < i; j++) { if (array[j].length > array[j + 1].length) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } return array; }
Create the powerset of a (multi)set. (The powerset contains very possible subsets of a (multi)set.) A multi-dimension array will be converted to a single-dimension array before the operation. Syntax: math.setPowerset(set) Examples: math.setPowerset([1, 2, 3]) // returns [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] See also: setCartesian @param {Array | Matrix} a A (multi)set @return {Array} The powerset of the (multi)set
_sort
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function erf1(y) { var ysq = y * y; var xnum = P[0][4] * ysq; var xden = ysq; var i; for (i = 0; i < 3; i += 1) { xnum = (xnum + P[0][i]) * ysq; xden = (xden + Q[0][i]) * ysq; } return y * (xnum + P[0][3]) / (xden + Q[0][3]); }
Approximates the error function erf() for x <= 0.46875 using this function: n erf(x) = x * sum (p_j * x^(2j)) / (q_j * x^(2j)) j=0
erf1
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function erfc2(y) { var xnum = P[1][8] * y; var xden = y; var i; for (i = 0; i < 7; i += 1) { xnum = (xnum + P[1][i]) * y; xden = (xden + Q[1][i]) * y; } var result = (xnum + P[1][7]) / (xden + Q[1][7]); var ysq = parseInt(y * 16) / 16; var del = (y - ysq) * (y + ysq); return Math.exp(-ysq * ysq) * Math.exp(-del) * result; }
Approximates the complement of the error function erfc() for 0.46875 <= x <= 4.0 using this function: n erfc(x) = e^(-x^2) * sum (p_j * x^j) / (q_j * x^j) j=0
erfc2
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function erfc3(y) { var ysq = 1 / (y * y); var xnum = P[2][5] * ysq; var xden = ysq; var i; for (i = 0; i < 4; i += 1) { xnum = (xnum + P[2][i]) * ysq; xden = (xden + Q[2][i]) * ysq; } var result = ysq * (xnum + P[2][4]) / (xden + Q[2][4]); result = (SQRPI - result) / y; ysq = parseInt(y * 16) / 16; var del = (y - ysq) * (y + ysq); return Math.exp(-ysq * ysq) * Math.exp(-del) * result; }
Approximates the complement of the error function erfc() for x > 4.0 using this function: erfc(x) = (e^(-x^2) / x) * [ 1/sqrt(pi) + n 1/(x^2) * sum (p_j * x^(-2j)) / (q_j * x^(-2j)) ] j=0
erfc3
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _mad(array) { array = flatten(array.valueOf()); if (array.length === 0) { throw new Error('Cannot calculate median absolute deviation (mad) of an empty array'); } try { var med = median(array); return median(map(array, function (value) { return abs(subtract(value, med)); })); } catch (err) { if (err instanceof TypeError && err.message.indexOf('median') !== -1) { throw new TypeError(err.message.replace('median', 'mad')); } else { throw improveErrorMessage(err, 'mad'); } } }
Compute the median absolute deviation of a matrix or a list with values. The median absolute deviation is defined as the median of the absolute deviations from the median. Syntax: math.mad(a, b, c, ...) math.mad(A) Examples: math.mad(10, 20, 30) // returns 10 math.mad([1, 2, 3]) // returns 1 math.mad([[1, 2, 3], [4, 5, 6]]) // returns 1.5 See also: median, mean, std, abs @param {Array | Matrix} array A single matrix or multiple scalar values. @return {*} The median absolute deviation.
_mad
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _mode(values) { values = flatten(values.valueOf()); var num = values.length; if (num === 0) { throw new Error('Cannot calculate mode of an empty array'); } var count = {}; var mode = []; var max = 0; for (var i = 0; i < values.length; i++) { var value = values[i]; if (isNumeric(value) && isNaN(value)) { throw new Error('Cannot calculate mode of an array containing NaN values'); } if (!(value in count)) { count[value] = 0; } count[value]++; if (count[value] === max) { mode.push(value); } else if (count[value] > max) { max = count[value]; mode = [value]; } } return mode; }
Calculates the mode in an 1-dimensional array @param {Array} values @return {Array} mode @private
_mode
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _prod(array) { var prod; deepForEach(array, function (value) { try { prod = prod === undefined ? value : multiply(prod, value); } catch (err) { throw improveErrorMessage(err, 'prod', value); } }); if (prod === undefined) { throw new Error('Cannot calculate prod of an empty array'); } return prod; }
Recursively calculate the product of an n-dimensional array @param {Array} array @return {number} prod @private
_prod
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function quantileSeq(data, probOrN, sorted) { var probArr, dataArr, one; if (arguments.length < 2 || arguments.length > 3) { throw new SyntaxError('Function quantileSeq requires two or three parameters'); } if (isCollection(data)) { sorted = sorted || false; if (typeof sorted === 'boolean') { dataArr = data.valueOf(); if (isNumber(probOrN)) { if (probOrN < 0) { throw new Error('N/prob must be non-negative'); } if (probOrN <= 1) { // quantileSeq([a, b, c, d, ...], prob[,sorted]) return _quantileSeq(dataArr, probOrN, sorted); } if (probOrN > 1) { // quantileSeq([a, b, c, d, ...], N[,sorted]) if (!isInteger(probOrN)) { throw new Error('N must be a positive integer'); } var nPlusOne = probOrN + 1; probArr = new Array(probOrN); for (var i = 0; i < probOrN;) { probArr[i] = _quantileSeq(dataArr, ++i / nPlusOne, sorted); } return probArr; } } if (type.isBigNumber(probOrN)) { if (probOrN.isNegative()) { throw new Error('N/prob must be non-negative'); } one = new probOrN.constructor(1); if (probOrN.lte(one)) { // quantileSeq([a, b, c, d, ...], prob[,sorted]) return new type.BigNumber(_quantileSeq(dataArr, probOrN, sorted)); } if (probOrN.gt(one)) { // quantileSeq([a, b, c, d, ...], N[,sorted]) if (!probOrN.isInteger()) { throw new Error('N must be a positive integer'); } // largest possible Array length is 2^32-1 // 2^32 < 10^15, thus safe conversion guaranteed var intN = probOrN.toNumber(); if (intN > 4294967295) { throw new Error('N must be less than or equal to 2^32-1, as that is the maximum length of an Array'); } var _nPlusOne = new type.BigNumber(intN + 1); probArr = new Array(intN); for (var _i = 0; _i < intN;) { probArr[_i] = new type.BigNumber(_quantileSeq(dataArr, new type.BigNumber(++_i).div(_nPlusOne), sorted)); } return probArr; } } if (Array.isArray(probOrN)) { // quantileSeq([a, b, c, d, ...], [prob1, prob2, ...][,sorted]) probArr = new Array(probOrN.length); for (var _i2 = 0; _i2 < probArr.length; ++_i2) { var currProb = probOrN[_i2]; if (isNumber(currProb)) { if (currProb < 0 || currProb > 1) { throw new Error('Probability must be between 0 and 1, inclusive'); } } else if (type.isBigNumber(currProb)) { one = new currProb.constructor(1); if (currProb.isNegative() || currProb.gt(one)) { throw new Error('Probability must be between 0 and 1, inclusive'); } } else { throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function } probArr[_i2] = _quantileSeq(dataArr, currProb, sorted); } return probArr; } throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function } throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function } throw new TypeError('Unexpected type of argument in function quantileSeq'); // FIXME: becomes redundant when converted to typed-function }
Compute the prob order quantile of a matrix or a list with values. The sequence is sorted and the middle value is returned. Supported types of sequence values are: Number, BigNumber, Unit Supported types of probability are: Number, BigNumber In case of a (multi dimensional) array or matrix, the prob order quantile of all elements will be calculated. Syntax: math.quantileSeq(A, prob[, sorted]) math.quantileSeq(A, [prob1, prob2, ...][, sorted]) math.quantileSeq(A, N[, sorted]) Examples: math.quantileSeq([3, -1, 5, 7], 0.5) // returns 4 math.quantileSeq([3, -1, 5, 7], [1/3, 2/3]) // returns [3, 5] math.quantileSeq([3, -1, 5, 7], 2) // returns [3, 5] math.quantileSeq([-1, 3, 5, 7], 0.5, true) // returns 4 See also: median, mean, min, max, sum, prod, std, var @param {Array, Matrix} data A single matrix or Array @param {Number, BigNumber, Array} probOrN prob is the order of the quantile, while N is the amount of evenly distributed steps of probabilities; only one of these options can be provided @param {Boolean} sorted=false is data sorted in ascending order @return {Number, BigNumber, Unit, Array} Quantile(s)
quantileSeq
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _quantileSeq(array, prob, sorted) { var flat = flatten(array); var len = flat.length; if (len === 0) { throw new Error('Cannot calculate quantile of an empty sequence'); } if (isNumber(prob)) { var _index = prob * (len - 1); var _fracPart = _index % 1; if (_fracPart === 0) { var value = sorted ? flat[_index] : partitionSelect(flat, _index); validate(value); return value; } var _integerPart = Math.floor(_index); var _left; var _right; if (sorted) { _left = flat[_integerPart]; _right = flat[_integerPart + 1]; } else { _right = partitionSelect(flat, _integerPart + 1); // max of partition is kth largest _left = flat[_integerPart]; for (var i = 0; i < _integerPart; ++i) { if (compare(flat[i], _left) > 0) { _left = flat[i]; } } } validate(_left); validate(_right); // Q(prob) = (1-f)*A[floor(index)] + f*A[floor(index)+1] return add(multiply(_left, 1 - _fracPart), multiply(_right, _fracPart)); } // If prob is a BigNumber var index = prob.times(len - 1); if (index.isInteger()) { index = index.toNumber(); var _value = sorted ? flat[index] : partitionSelect(flat, index); validate(_value); return _value; } var integerPart = index.floor(); var fracPart = index.minus(integerPart); var integerPartNumber = integerPart.toNumber(); var left; var right; if (sorted) { left = flat[integerPartNumber]; right = flat[integerPartNumber + 1]; } else { right = partitionSelect(flat, integerPartNumber + 1); // max of partition is kth largest left = flat[integerPartNumber]; for (var _i3 = 0; _i3 < integerPartNumber; ++_i3) { if (compare(flat[_i3], left) > 0) { left = flat[_i3]; } } } validate(left); validate(right); // Q(prob) = (1-f)*A[floor(index)] + f*A[floor(index)+1] var one = new fracPart.constructor(1); return add(multiply(left, one.minus(fracPart)), multiply(right, fracPart)); }
Calculate the prob order quantile of an n-dimensional array. @param {Array} array @param {Number, BigNumber} prob @param {Boolean} sorted @return {Number, BigNumber, Unit} prob order quantile @private
_quantileSeq
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _print(template, values, options) { return template.replace(/\$([\w.]+)/g, function (original, key) { var keys = key.split('.'); var value = values[keys.shift()]; while (keys.length && value !== undefined) { var k = keys.shift(); value = k ? value[k] : value + '.'; } if (value !== undefined) { if (!isString(value)) { return format(value, options); } else { return value; } } return original; }); }
Interpolate values into a string template. @param {string} template @param {Object} values @param {number | Object} [options] @returns {string} Interpolated string @private
_print
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _csch(x) { // consider values close to zero (+/-) if (x === 0) { return Number.POSITIVE_INFINITY; } else { return Math.abs(2 / (Math.exp(x) - Math.exp(-x))) * sign(x); } }
Calculate the hyperbolic cosecant of a number @param {number} x @returns {number} @private
_csch
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var apply = load(__webpack_require__(96)); // @see: comment of concat itself return typed('apply', { '...any': function any(args) { // change dim from one-based to zero-based var dim = args[1]; if (type.isNumber(dim)) { args[1] = dim - 1; } else if (type.isBigNumber(dim)) { args[1] = dim.minus(1); } try { return apply.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
Attach a transform function to math.apply Adds a property transform containing the transform function. This transform changed the last `dim` parameter of function apply from one-based to zero based
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var column = load(__webpack_require__(143)); // @see: comment of column itself return typed('column', { '...any': function any(args) { // change last argument from zero-based to one-based var lastIndex = args.length - 1; var last = args[lastIndex]; if (type.isNumber(last)) { args[lastIndex] = last - 1; } try { return column.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
Attach a transform function to matrix.column Adds a property transform containing the transform function. This transform changed the last `index` parameter of function column from zero-based to one-based
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var concat = load(__webpack_require__(78)); // @see: comment of concat itself return typed('concat', { '...any': function any(args) { // change last argument from one-based to zero-based var lastIndex = args.length - 1; var last = args[lastIndex]; if (type.isNumber(last)) { args[lastIndex] = last - 1; } else if (type.isBigNumber(last)) { args[lastIndex] = last.minus(1); } try { return concat.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
Attach a transform function to math.range Adds a property transform containing the transform function. This transform changed the last `dim` parameter of function concat from one-based to zero based
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var compileInlineExpression = load(__webpack_require__(102)); var matrix = load(__webpack_require__(0)); function filterTransform(args, math, scope) { var x, callback; if (args[0]) { x = args[0].compile().eval(scope); } if (args[1]) { if (type.isSymbolNode(args[1]) || type.isFunctionAssignmentNode(args[1])) { // a function pointer, like filter([3, -2, 5], myTestFunction) callback = args[1].compile().eval(scope); } else { // an expression like filter([3, -2, 5], x > 0) callback = compileInlineExpression(args[1], math, scope); } } return filter(x, callback); } filterTransform.rawArgs = true; // one based version of function filter var filter = typed('filter', { 'Array, function': _filter, 'Matrix, function': function MatrixFunction(x, test) { return matrix(_filter(x.toArray(), test)); }, 'Array, RegExp': filterRegExp, 'Matrix, RegExp': function MatrixRegExp(x, test) { return matrix(filterRegExp(x.toArray(), test)); } }); filter.toTex = undefined; // use default template return filterTransform; }
Attach a transform function to math.filter Adds a property transform containing the transform function. This transform adds support for equations as test function for math.filter, so you can do something like 'filter([3, -2, 5], x > 0)'.
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function filterTransform(args, math, scope) { var x, callback; if (args[0]) { x = args[0].compile().eval(scope); } if (args[1]) { if (type.isSymbolNode(args[1]) || type.isFunctionAssignmentNode(args[1])) { // a function pointer, like filter([3, -2, 5], myTestFunction) callback = args[1].compile().eval(scope); } else { // an expression like filter([3, -2, 5], x > 0) callback = compileInlineExpression(args[1], math, scope); } } return filter(x, callback); }
Attach a transform function to math.filter Adds a property transform containing the transform function. This transform adds support for equations as test function for math.filter, so you can do something like 'filter([3, -2, 5], x > 0)'.
filterTransform
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _filter(x, callback) { // figure out what number of arguments the callback function expects var args = maxArgumentCount(callback); return filter(x, function (value, index, array) { // invoke the callback function with the right number of arguments if (args === 1) { return callback(value); } else if (args === 2) { return callback(value, [index + 1]); } else { // 3 or -1 return callback(value, [index + 1], array); } }); }
Filter values in a callback given a callback function !!! Passes a one-based index !!! @param {Array} x @param {Function} callback @return {Array} Returns the filtered array @private
_filter
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var compileInlineExpression = load(__webpack_require__(102)); function forEachTransform(args, math, scope) { var x, callback; if (args[0]) { x = args[0].compile().eval(scope); } if (args[1]) { if (type.isSymbolNode(args[1]) || type.isFunctionAssignmentNode(args[1])) { // a function pointer, like forEach([3, -2, 5], myTestFunction) callback = args[1].compile().eval(scope); } else { // an expression like forEach([3, -2, 5], x > 0 ? callback1(x) : callback2(x) ) callback = compileInlineExpression(args[1], math, scope); } } return _forEach(x, callback); } forEachTransform.rawArgs = true; // one-based version of forEach var _forEach = typed('forEach', { 'Array | Matrix, function': function ArrayMatrixFunction(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)) { forEach(value, function (child, i) { // we create a copy of the index array and append the new index value recurse(child, index.concat(i + 1)); // one based index, hence i+1 }); } else { // invoke the callback function with the right number of arguments if (args === 1) { callback(value); } else if (args === 2) { callback(value, index); } else { // 3 or -1 callback(value, index, array); } } }; recurse(array.valueOf(), []); // pass Array } }); return forEachTransform; }
Attach a transform function to math.forEach Adds a property transform containing the transform function. This transform creates a one-based index instead of a zero-based index
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function forEachTransform(args, math, scope) { var x, callback; if (args[0]) { x = args[0].compile().eval(scope); } if (args[1]) { if (type.isSymbolNode(args[1]) || type.isFunctionAssignmentNode(args[1])) { // a function pointer, like forEach([3, -2, 5], myTestFunction) callback = args[1].compile().eval(scope); } else { // an expression like forEach([3, -2, 5], x > 0 ? callback1(x) : callback2(x) ) callback = compileInlineExpression(args[1], math, scope); } } return _forEach(x, callback); }
Attach a transform function to math.forEach Adds a property transform containing the transform function. This transform creates a one-based index instead of a zero-based index
forEachTransform
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
recurse = function recurse(value, index) { if (Array.isArray(value)) { forEach(value, function (child, i) { // we create a copy of the index array and append the new index value recurse(child, index.concat(i + 1)); // one based index, hence i+1 }); } else { // invoke the callback function with the right number of arguments if (args === 1) { callback(value); } else if (args === 2) { callback(value, index); } else { // 3 or -1 callback(value, index, array); } } }
Attach a transform function to math.forEach Adds a property transform containing the transform function. This transform creates a one-based index instead of a zero-based index
recurse
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load) { return function indexTransform() { var args = []; for (var i = 0, ii = arguments.length; i < ii; i++) { var arg = arguments[i]; // change from one-based to zero based, and convert BigNumber to number if (type.isRange(arg)) { arg.start--; arg.end -= arg.step > 0 ? 0 : 2; } else if (arg && arg.isSet === true) { arg = arg.map(function (v) { return v - 1; }); } else if (type.isArray(arg) || type.isMatrix(arg)) { arg = arg.map(function (v) { return v - 1; }); } else if (type.isNumber(arg)) { arg--; } else if (type.isBigNumber(arg)) { arg = arg.toNumber() - 1; } else if (typeof arg === 'string') {// leave as is } else { throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range'); } args[i] = arg; } var res = new type.Index(); type.Index.apply(res, args); return res; }; }
Attach a transform function to math.index Adds a property transform containing the transform function. This transform creates a one-based index instead of a zero-based index
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var compileInlineExpression = load(__webpack_require__(102)); var matrix = load(__webpack_require__(0)); function mapTransform(args, math, scope) { var x, callback; if (args[0]) { x = args[0].compile().eval(scope); } if (args[1]) { if (type.isSymbolNode(args[1]) || type.isFunctionAssignmentNode(args[1])) { // a function pointer, like filter([3, -2, 5], myTestFunction) callback = args[1].compile().eval(scope); } else { // an expression like filter([3, -2, 5], x > 0) callback = compileInlineExpression(args[1], math, scope); } } return map(x, callback); } mapTransform.rawArgs = true; // one-based version of map function var map = typed('map', { 'Array, function': function ArrayFunction(x, callback) { return _map(x, callback, x); }, 'Matrix, function': function MatrixFunction(x, callback) { return matrix(_map(x.valueOf(), callback, x)); } }); return mapTransform; }
Attach a transform function to math.map Adds a property transform containing the transform function. This transform creates a one-based index instead of a zero-based index
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function mapTransform(args, math, scope) { var x, callback; if (args[0]) { x = args[0].compile().eval(scope); } if (args[1]) { if (type.isSymbolNode(args[1]) || type.isFunctionAssignmentNode(args[1])) { // a function pointer, like filter([3, -2, 5], myTestFunction) callback = args[1].compile().eval(scope); } else { // an expression like filter([3, -2, 5], x > 0) callback = compileInlineExpression(args[1], math, scope); } } return map(x, callback); }
Attach a transform function to math.map Adds a property transform containing the transform function. This transform creates a one-based index instead of a zero-based index
mapTransform
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function _map(array, callback, orig) { // figure out what number of arguments the callback function expects var argsCount = maxArgumentCount(callback); function recurse(value, index) { if (Array.isArray(value)) { return map(value, function (child, i) { // we create a copy of the index array and append the new index value return recurse(child, index.concat(i + 1)); // one based index, hence i + 1 }); } else { // invoke the (typed) callback function with the right number of arguments if (argsCount === 1) { return callback(value); } else if (argsCount === 2) { return callback(value, index); } else { // 3 or -1 return callback(value, index, orig); } } } return recurse(array, []); }
Map for a multi dimensional array. One-based indexes @param {Array} array @param {function} callback @param {Array} orig @return {Array} @private
_map
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function recurse(value, index) { if (Array.isArray(value)) { return map(value, function (child, i) { // we create a copy of the index array and append the new index value return recurse(child, index.concat(i + 1)); // one based index, hence i + 1 }); } else { // invoke the (typed) callback function with the right number of arguments if (argsCount === 1) { return callback(value); } else if (argsCount === 2) { return callback(value, index); } else { // 3 or -1 return callback(value, index, orig); } } }
Map for a multi dimensional array. One-based indexes @param {Array} array @param {function} callback @param {Array} orig @return {Array} @private
recurse
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var max = load(__webpack_require__(98)); return typed('max', { '...any': function any(args) { // change last argument dim from one-based to zero-based if (args.length === 2 && isCollection(args[0])) { var dim = args[1]; if (type.isNumber(dim)) { args[1] = dim - 1; } else if (type.isBigNumber(dim)) { args[1] = dim.minus(1); } } try { return max.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
Attach a transform function to math.max Adds a property transform containing the transform function. This transform changed the last `dim` parameter of function max from one-based to zero based
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var mean = load(__webpack_require__(152)); return typed('mean', { '...any': function any(args) { // change last argument dim from one-based to zero-based if (args.length === 2 && isCollection(args[0])) { var dim = args[1]; if (type.isNumber(dim)) { args[1] = dim - 1; } else if (type.isBigNumber(dim)) { args[1] = dim.minus(1); } } try { return mean.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
Attach a transform function to math.mean Adds a property transform containing the transform function. This transform changed the last `dim` parameter of function mean from one-based to zero based
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var min = load(__webpack_require__(153)); return typed('min', { '...any': function any(args) { // change last argument dim from one-based to zero-based if (args.length === 2 && isCollection(args[0])) { var dim = args[1]; if (type.isNumber(dim)) { args[1] = dim - 1; } else if (type.isBigNumber(dim)) { args[1] = dim.minus(1); } } try { return min.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
Attach a transform function to math.min Adds a property transform containing the transform function. This transform changed the last `dim` parameter of function min from one-based to zero based
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var range = load(__webpack_require__(77)); return typed('range', { '...any': function any(args) { var lastIndex = args.length - 1; var last = args[lastIndex]; if (typeof last !== 'boolean') { // append a parameter includeEnd=true args.push(true); } return range.apply(null, args); } }); }
Attach a transform function to math.range Adds a property transform containing the transform function. This transform creates a range which includes the end value
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var std = load(__webpack_require__(154)); return typed('std', { '...any': function any(args) { // change last argument dim from one-based to zero-based if (args.length >= 2 && isCollection(args[0])) { var dim = args[1]; if (type.isNumber(dim)) { args[1] = dim - 1; } else if (type.isBigNumber(dim)) { args[1] = dim.minus(1); } } try { return std.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
Attach a transform function to math.std Adds a property transform containing the transform function. This transform changed the `dim` parameter of function std from one-based to zero based
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var row = load(__webpack_require__(146)); // @see: comment of row itself return typed('row', { '...any': function any(args) { // change last argument from zero-based to one-based var lastIndex = args.length - 1; var last = args[lastIndex]; if (type.isNumber(last)) { args[lastIndex] = last - 1; } try { return row.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
Attach a transform function to matrix.row Adds a property transform containing the transform function. This transform changed the last `index` parameter of function row from zero-based to one-based
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var subset = load(__webpack_require__(23)); return typed('subset', { '...any': function any(args) { try { return subset.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
Attach a transform function to math.subset Adds a property transform containing the transform function. This transform creates a range which includes the end value
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var sum = load(__webpack_require__(99)); return typed('sum', { '...any': function any(args) { // change last argument dim from one-based to zero-based if (args.length === 2 && isCollection(args[0])) { var dim = args[1]; if (type.isNumber(dim)) { args[1] = dim - 1; } else if (type.isBigNumber(dim)) { args[1] = dim.minus(1); } } try { return sum.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
Attach a transform function to math.sum Adds a property transform containing the transform function. This transform changed the last `dim` parameter of function mean from one-based to zero based
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function factory(type, config, load, typed) { var variance = load(__webpack_require__(101)); return typed('var', { '...any': function any(args) { // change last argument dim from one-based to zero-based if (args.length >= 2 && isCollection(args[0])) { var dim = args[1]; if (type.isNumber(dim)) { args[1] = dim - 1; } else if (type.isBigNumber(dim)) { args[1] = dim.minus(1); } } try { return variance.apply(null, args); } catch (err) { throw errorTransform(err); } } }); }
Attach a transform function to math.var Adds a property transform containing the transform function. This transform changed the `dim` parameter of function var from one-based to zero based
factory
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
function Help(doc) { if (!(this instanceof Help)) { throw new SyntaxError('Constructor must be called with the new operator'); } if (!doc) throw new Error('Argument "doc" missing'); this.doc = doc; }
Documentation object @param {Object} doc Object containing properties: {string} name {string} category {string} description {string[]} syntax {string[]} examples {string[]} seealso @constructor
Help
javascript
grimalschi/calque
math.js
https://github.com/grimalschi/calque/blob/master/math.js
MIT
render() { if (this.props.children instanceof Function) { return this.props.children({ isVisible: this.state.isVisible, visibilityRect: this.state.visibilityRect }); } return React.Children.only(this.props.children); }
Check if the element is within the visible viewport
render
javascript
joshwnj/react-visibility-sensor
visibility-sensor.js
https://github.com/joshwnj/react-visibility-sensor/blob/master/visibility-sensor.js
MIT
function language(y, mo, w, d, h, m, s, ms, decimal) { /** @type {Language} */ var result = { y: y, mo: mo, w: w, d: d, h: h, m: m, s: s, ms: ms }; if (typeof decimal !== "undefined") { result.decimal = decimal; } return result; }
@internal @param {Pick<Required<Options>, "language" | "fallbacks" | "languages">} options @throws {Error} Throws an error if language is not found. @returns {Language}
language
javascript
EvanHahn/HumanizeDuration.js
humanize-duration.js
https://github.com/EvanHahn/HumanizeDuration.js/blob/master/humanize-duration.js
Unlicense
function getArabicForm(c) { if (c === 2) { return 1; } if (c > 2 && c < 11) { return 2; } return 0; }
@internal @param {Pick<Required<Options>, "language" | "fallbacks" | "languages">} options @throws {Error} Throws an error if language is not found. @returns {Language}
getArabicForm
javascript
EvanHahn/HumanizeDuration.js
humanize-duration.js
https://github.com/EvanHahn/HumanizeDuration.js/blob/master/humanize-duration.js
Unlicense
function getPolishForm(c) { if (c === 1) { return 0; } if (Math.floor(c) !== c) { return 1; } if (c % 10 >= 2 && c % 10 <= 4 && !(c % 100 > 10 && c % 100 < 20)) { return 2; } return 3; }
@internal @param {Pick<Required<Options>, "language" | "fallbacks" | "languages">} options @throws {Error} Throws an error if language is not found. @returns {Language}
getPolishForm
javascript
EvanHahn/HumanizeDuration.js
humanize-duration.js
https://github.com/EvanHahn/HumanizeDuration.js/blob/master/humanize-duration.js
Unlicense
function getSlavicForm(c) { if (Math.floor(c) !== c) { return 2; } if ( (c % 100 >= 5 && c % 100 <= 20) || (c % 10 >= 5 && c % 10 <= 9) || c % 10 === 0 ) { return 0; } if (c % 10 === 1) { return 1; } if (c > 1) { return 2; } return 0; }
@internal @param {Piece} piece @param {Language} language @param {Pick<Required<Options>, "decimal" | "spacer" | "maxDecimalPoints" | "digitReplacements">} options
getSlavicForm
javascript
EvanHahn/HumanizeDuration.js
humanize-duration.js
https://github.com/EvanHahn/HumanizeDuration.js/blob/master/humanize-duration.js
Unlicense
function formatPieces(pieces, options) { var language = getLanguage(options); if (!pieces.length) { var units = options.units; var smallestUnitName = units[units.length - 1]; return renderPiece( { unitName: smallestUnitName, unitCount: 0 }, language, options ); } var conjunction = options.conjunction; var serialComma = options.serialComma; var delimiter; if (has(options, "delimiter")) { delimiter = options.delimiter; } else if (has(language, "delimiter")) { delimiter = language.delimiter; } else { delimiter = ", "; } /** @type {string[]} */ var renderedPieces = []; for (var i = 0; i < pieces.length; i++) { renderedPieces.push(renderPiece(pieces[i], language, options)); } if (!conjunction || pieces.length === 1) { return renderedPieces.join(delimiter); } if (pieces.length === 2) { return renderedPieces.join(conjunction); } return ( renderedPieces.slice(0, -1).join(delimiter) + (serialComma ? "," : "") + conjunction + renderedPieces.slice(-1) ); }
Humanize a duration. This is a wrapper around the default humanizer.
formatPieces
javascript
EvanHahn/HumanizeDuration.js
humanize-duration.js
https://github.com/EvanHahn/HumanizeDuration.js/blob/master/humanize-duration.js
Unlicense
function humanizer(passedOptions) { /** * @param {number} ms * @param {Options} [humanizerOptions] * @returns {string} */ var result = function humanizer(ms, humanizerOptions) { // Make sure we have a positive number. // // Has the nice side-effect of converting things to numbers. For example, // converts `"123"` and `Number(123)` to `123`. ms = Math.abs(ms); var options = assign({}, result, humanizerOptions || {}); var pieces = getPieces(ms, options); return formatPieces(pieces, options); }; return assign( result, { language: "en", spacer: " ", conjunction: "", serialComma: true, units: ["y", "mo", "w", "d", "h", "m", "s"], languages: {}, round: false, unitMeasures: { y: 31557600000, mo: 2629800000, w: 604800000, d: 86400000, h: 3600000, m: 60000, s: 1000, ms: 1 } }, passedOptions ); }
Humanize a duration. This is a wrapper around the default humanizer.
humanizer
javascript
EvanHahn/HumanizeDuration.js
humanize-duration.js
https://github.com/EvanHahn/HumanizeDuration.js/blob/master/humanize-duration.js
Unlicense
result = function humanizer(ms, humanizerOptions) { // Make sure we have a positive number. // // Has the nice side-effect of converting things to numbers. For example, // converts `"123"` and `Number(123)` to `123`. ms = Math.abs(ms); var options = assign({}, result, humanizerOptions || {}); var pieces = getPieces(ms, options); return formatPieces(pieces, options); }
Humanize a duration. This is a wrapper around the default humanizer.
result
javascript
EvanHahn/HumanizeDuration.js
humanize-duration.js
https://github.com/EvanHahn/HumanizeDuration.js/blob/master/humanize-duration.js
Unlicense
options = (language) => ({ language, delimiter: "+", units: ["y", "mo", "w", "d", "h", "m", "s", "ms"], })
@param {string} language @returns {import("../humanize-duration.js").Options}
options
javascript
EvanHahn/HumanizeDuration.js
test/languages.js
https://github.com/EvanHahn/HumanizeDuration.js/blob/master/test/languages.js
Unlicense
options = (language) => ({ language, delimiter: "+", units: ["y", "mo", "w", "d", "h", "m", "s", "ms"], })
@param {string} language @returns {import("../humanize-duration.js").Options}
options
javascript
EvanHahn/HumanizeDuration.js
test/languages.js
https://github.com/EvanHahn/HumanizeDuration.js/blob/master/test/languages.js
Unlicense
readPairs = async (filePath) => { /** @type {Array<[number, string]>} */ const result = []; const parser = fs .createReadStream(filePath) .pipe(parseCsv({ delimiter: "\t" })); for await (const [msString, expectedResult] of parser) { result.push([parseFloat(msString), expectedResult]); } return result; }
@param {string} filePath @returns {Promise<Array<[number, string]>>}
readPairs
javascript
EvanHahn/HumanizeDuration.js
test/languages.js
https://github.com/EvanHahn/HumanizeDuration.js/blob/master/test/languages.js
Unlicense
readPairs = async (filePath) => { /** @type {Array<[number, string]>} */ const result = []; const parser = fs .createReadStream(filePath) .pipe(parseCsv({ delimiter: "\t" })); for await (const [msString, expectedResult] of parser) { result.push([parseFloat(msString), expectedResult]); } return result; }
@param {string} filePath @returns {Promise<Array<[number, string]>>}
readPairs
javascript
EvanHahn/HumanizeDuration.js
test/languages.js
https://github.com/EvanHahn/HumanizeDuration.js/blob/master/test/languages.js
Unlicense
function Renderer() { /** * Renderer#rules -> Object * * Contains render rules for tokens. Can be updated and extended. * * ##### Example * * ```javascript * var md = require('markdown-it')(); * * md.renderer.rules.strong_open = function () { return '<b>'; }; * md.renderer.rules.strong_close = function () { return '</b>'; }; * * var result = md.renderInline(...); * ``` * * Each rule is called as independed static function with fixed signature: * * ```javascript * function my_token_render(tokens, idx, options, env, renderer) { * // ... * return renderedHTML; * } * ``` * * See [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js) * for more details and examples. **/ this.rules = assign({}, default_rules); }
Renderer.renderToken(tokens, idx, options) -> String - tokens (Array): list of tokens - idx (Numbed): token index to render - options (Object): params of parser instance Default token renderer. Can be overriden by custom function in [[Renderer#rules]].
Renderer
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
function Ruler() { // List of added rules. Each element is: // // { // name: XXX, // enabled: Boolean, // fn: Function(), // alt: [ name2, name3 ] // } // this.__rules__ = []; // Cached rule chains. // // First level - chain name, '' for default. // Second level - diginal anchor for fast filtering by charcodes. // this.__cache__ = null; }
Ruler.at(name, fn [, options]) - name (String): rule name to replace. - fn (Function): new rule function. - options (Object): new rule options (not mandatory). Replace rule by name with new function & options. Throws error if name not found. ##### Options: - __alt__ - array with names of "alternate" chains. ##### Example Replace existing typorgapher replacement rule with new one: ```javascript var md = require('markdown-it')(); md.core.ruler.at('replacements', function replace(state) { //... }); ```
Ruler
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
function StateCore(src, md, env) { this.src = src; this.env = env; this.tokens = []; this.inlineMode = false; this.md = md; // link to parser instance }
Token#block -> Boolean True for block-level tokens, false for inline tokens. Used in renderer to calculate line breaks
StateCore
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
function Token(type, tag, nesting) { /** * Token#type -> String * * Type of the token (string, e.g. "paragraph_open") **/ this.type = type; /** * Token#tag -> String * * html tag name, e.g. "p" **/ this.tag = tag; /** * Token#attrs -> Array * * Html attributes. Format: `[ [ name1, value1 ], [ name2, value2 ] ]` **/ this.attrs = null; /** * Token#map -> Array * * Source map info. Format: `[ line_begin, line_end ]` **/ this.map = null; /** * Token#nesting -> Number * * Level change (number in {-1, 0, 1} set), where: * * - `1` means the tag is opening * - `0` means the tag is self-closing * - `-1` means the tag is closing **/ this.nesting = nesting; /** * Token#level -> Number * * nesting level, the same as `state.level` **/ this.level = 0; /** * Token#children -> Array * * An array of child nodes (inline and img tokens) **/ this.children = null; /** * Token#content -> String * * In a case of self-closing tag (code, html, fence, etc.), * it has contents of this tag. **/ this.content = ''; /** * Token#markup -> String * * '*' or '_' for emphasis, fence string for fence, etc. **/ this.markup = ''; /** * Token#info -> String * * fence infostring **/ this.info = ''; /** * Token#meta -> Object * * A place for plugins to store an arbitrary data **/ this.meta = null; /** * Token#block -> Boolean * * True for block-level tokens, false for inline tokens. * Used in renderer to calculate line breaks **/ this.block = false; /** * Token#hidden -> Boolean * * If it's true, ignore this element when rendering. Used for tight lists * to hide paragraphs. **/ this.hidden = false; }
Token.attrIndex(name) -> Number Search attribute index by name.
Token
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
function ParserInline() { var i; /** * ParserInline#ruler -> Ruler * * [[Ruler]] instance. Keep configuration of inline rules. **/ this.ruler = new Ruler(); for (i = 0; i < _rules.length; i++) { this.ruler.push(_rules[i][0], _rules[i][1]); } /** * ParserInline#ruler2 -> Ruler * * [[Ruler]] instance. Second ruler used for post-processing * (e.g. in emphasis-like rules). **/ this.ruler2 = new Ruler(); for (i = 0; i < _rules2.length; i++) { this.ruler2.push(_rules2[i][0], _rules2[i][1]); } }
ParserInline#ruler2 -> Ruler [[Ruler]] instance. Second ruler used for post-processing (e.g. in emphasis-like rules).
ParserInline
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
function schemaError(name, val) { throw new Error('(LinkifyIt) Invalid schema "' + name + '": ' + val); }
class Match Match result. Single element of array, returned by [[LinkifyIt#match]]
schemaError
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
function Match(self, shift) { var start = self.__index__, end = self.__last_index__, text = self.__text_cache__.slice(start, end); /** * Match#schema -> String * * Prefix (protocol) for matched string. **/ this.schema = self.__schema__.toLowerCase(); /** * Match#index -> Number * * First position of matched string. **/ this.index = start + shift; /** * Match#lastIndex -> Number * * Next position after matched string. **/ this.lastIndex = end + shift; /** * Match#raw -> String * * Matched string. **/ this.raw = text; /** * Match#text -> String * * Notmalized text of matched string. **/ this.text = text; /** * Match#url -> String * * Normalized url of matched string. **/ this.url = text; }
new LinkifyIt(schemas, options) - schemas (Object): Optional. Additional schemas to validate (prefix/validator) - options (Object): { fuzzyLink|fuzzyEmail|fuzzyIP: true|false } Creates new linkifier instance with optional additional schemas. Can be called without `new` keyword for convenience. By default understands: - `http(s)://...` , `ftp://...`, `mailto:...` & `//...` links - "fuzzy" links and emails (example.com, [email protected]). `schemas` is an object, where each key/value describes protocol/rule: - __key__ - link prefix (usually, protocol name with `:` at the end, `skype:` for example). `linkify-it` makes shure that prefix is not preceeded with alphanumeric char and symbols. Only whitespaces and punctuation allowed. - __value__ - rule to check tail after link prefix - _String_ - just alias to existing rule - _Object_ - _validate_ - validator function (should return matched length on success), or `RegExp`. - _normalize_ - optional function to normalize text & url of matched result (for example, for @twitter mentions). `options`: - __fuzzyLink__ - recognige URL-s without `http(s):` prefix. Default `true`. - __fuzzyIP__ - allow IPs in fuzzy links above. Can conflict with some texts like version numbers. Default `false`. - __fuzzyEmail__ - recognize emails without `mailto:` prefix.
Match
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
function createMatch(self, shift) { var match = new Match(self, shift); self.__compiled__[match.schema].normalize(match, self); return match; }
chainable LinkifyIt#add(schema, definition) - schema (String): rule name (fixed pattern prefix) - definition (String|RegExp|Object): schema definition Add new rule definition. See constructor description for details.
createMatch
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
function LinkifyIt(schemas, options) { if (!(this instanceof LinkifyIt)) { return new LinkifyIt(schemas, options); } if (!options) { if (isOptionsObj(schemas)) { options = schemas; schemas = {}; } } this.__opts__ = assign({}, defaultOptions, options); // Cache last tested result. Used to skip repeating steps on next `match` call. this.__index__ = -1; this.__last_index__ = -1; // Next scan position this.__schema__ = ''; this.__text_cache__ = ''; this.__schemas__ = assign({}, defaultSchemas, schemas); this.__compiled__ = {}; this.__tlds__ = tlds_default; this.__tlds_replaced__ = false; this.re = {}; compile(this); }
LinkifyIt#test(text) -> Boolean Searches linkifiable pattern and returns `true` on success or `false` on fail.
LinkifyIt
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
function error(type) { throw new RangeError(errors[type]); }
Creates an array containing the numeric code points of each Unicode character in the string. While JavaScript uses UCS-2 internally, this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. @see `punycode.ucs2.encode` @see <https://mathiasbynens.be/notes/javascript-encoding> @memberOf punycode.ucs2 @name decode @param {String} string The Unicode input string (UCS-2). @returns {Array} The new array of code points.
error
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; }
Creates an array containing the numeric code points of each Unicode character in the string. While JavaScript uses UCS-2 internally, this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. @see `punycode.ucs2.encode` @see <https://mathiasbynens.be/notes/javascript-encoding> @memberOf punycode.ucs2 @name decode @param {String} string The Unicode input string (UCS-2). @returns {Array} The new array of code points.
map
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; }
Creates a string based on an array of numeric code points. @see `punycode.ucs2.decode` @memberOf punycode.ucs2 @name encode @param {Array} codePoints The array of numeric code points. @returns {String} The new Unicode string (UCS-2).
mapDomain
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; }
Converts a basic code point into a digit/integer. @see `digitToBasic()` @private @param {Number} codePoint The basic numeric code point value. @returns {Number} The numeric value of a basic code point (for use in representing integers) in the range `0` to `base - 1`, or `base` if the code point does not represent a value.
ucs2decode
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); }
Converts a Punycode string of ASCII-only symbols to a string of Unicode symbols. @memberOf punycode @param {String} input The Punycode string of ASCII-only symbols. @returns {String} The resulting string of Unicode symbols.
ucs2encode
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
repeat = function repeat(string, num) { return new Array(num + 1).join(string); }
Clones (copies) an Object using deep copying. This function supports circular references by default, but if you are certain there are no circular references in your object, you can save some CPU time by calling clone(obj, false). Caution: if `circular` is false and `parent` contains circular references, your program may enter an infinite loop and crash. @param `parent` - the object to be cloned @param `circular` - set to true if the object to be cloned may contain circular references. (optional - true by default) @param `depth` - set to a number if the object is only to be cloned to a particular depth. (optional - defaults to Infinity) @param `prototype` - sets the prototype to be used when cloning an object. (optional - defaults to parent prototype). @param `includeNonEnumerable` - set to true if the non-enumerable properties should be cloned as well. Non-enumerable properties on the prototype chain will be ignored. (optional - false by default)
repeat
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
makeSafe = function makeSafe(string, headingIds) { var key = (0, _uslug2.default)(string); // slugify if (!headingIds[key]) { headingIds[key] = 0; } headingIds[key]++; return key + (headingIds[key] > 1 ? "-" + headingIds[key] : ""); }
Clones (copies) an Object using deep copying. This function supports circular references by default, but if you are certain there are no circular references in your object, you can save some CPU time by calling clone(obj, false). Caution: if `circular` is false and `parent` contains circular references, your program may enter an infinite loop and crash. @param `parent` - the object to be cloned @param `circular` - set to true if the object to be cloned may contain circular references. (optional - true by default) @param `depth` - set to a number if the object is only to be cloned to a particular depth. (optional - defaults to Infinity) @param `prototype` - sets the prototype to be used when cloning an object. (optional - defaults to parent prototype). @param `includeNonEnumerable` - set to true if the non-enumerable properties should be cloned as well. Non-enumerable properties on the prototype chain will be ignored. (optional - false by default)
makeSafe
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
space = function space() { return _extends({}, new Token("text", "", 0), { content: " " }); }
Clones (copies) an Object using deep copying. This function supports circular references by default, but if you are certain there are no circular references in your object, you can save some CPU time by calling clone(obj, false). Caution: if `circular` is false and `parent` contains circular references, your program may enter an infinite loop and crash. @param `parent` - the object to be cloned @param `circular` - set to true if the object to be cloned may contain circular references. (optional - true by default) @param `depth` - set to a number if the object is only to be cloned to a particular depth. (optional - defaults to Infinity) @param `prototype` - sets the prototype to be used when cloning an object. (optional - defaults to parent prototype). @param `includeNonEnumerable` - set to true if the non-enumerable properties should be cloned as well. Non-enumerable properties on the prototype chain will be ignored. (optional - false by default)
space
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT
renderAnchorLinkSymbol = function renderAnchorLinkSymbol(options) { if (options.anchorLinkSymbolClassName) { return [_extends({}, new Token("span_open", "span", 1), { attrs: [["class", options.anchorLinkSymbolClassName]] }), _extends({}, new Token("text", "", 0), { content: options.anchorLinkSymbol }), new Token("span_close", "span", -1)]; } else { return [_extends({}, new Token("text", "", 0), { content: options.anchorLinkSymbol })]; } }
Clones (copies) an Object using deep copying. This function supports circular references by default, but if you are certain there are no circular references in your object, you can save some CPU time by calling clone(obj, false). Caution: if `circular` is false and `parent` contains circular references, your program may enter an infinite loop and crash. @param `parent` - the object to be cloned @param `circular` - set to true if the object to be cloned may contain circular references. (optional - true by default) @param `depth` - set to a number if the object is only to be cloned to a particular depth. (optional - defaults to Infinity) @param `prototype` - sets the prototype to be used when cloning an object. (optional - defaults to parent prototype). @param `includeNonEnumerable` - set to true if the non-enumerable properties should be cloned as well. Non-enumerable properties on the prototype chain will be ignored. (optional - false by default)
renderAnchorLinkSymbol
javascript
arturssmirnovs/github-profile-readme-generator
js/markdown.js
https://github.com/arturssmirnovs/github-profile-readme-generator/blob/master/js/markdown.js
MIT