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 |
---|---|---|---|---|---|---|---|
Scheduler = function Scheduler( element, options ) {
var self = this;
this.$element = $( element );
this.options = $.extend( {}, $.fn.scheduler.defaults, options );
// cache elements
this.$startDate = this.$element.find( '.start-datetime .start-date' );
this.$startTime = this.$element.find( '.start-datetime .start-time' );
this.$timeZone = this.$element.find( '.timezone-container .timezone' );
this.$repeatIntervalPanel = this.$element.find( '.repeat-every-panel' );
this.$repeatIntervalSelect = this.$element.find( '.repeat-options' );
this.$repeatIntervalSpinbox = this.$element.find( '.repeat-every' );
this.$repeatIntervalTxt = this.$element.find( '.repeat-every-text' );
this.$end = this.$element.find( '.repeat-end' );
this.$endSelect = this.$end.find( '.end-options' );
this.$endAfter = this.$end.find( '.end-after' );
this.$endDate = this.$end.find( '.end-on-date' );
// panels
this.$recurrencePanels = this.$element.find( '.repeat-panel' );
this.$repeatIntervalSelect.selectlist();
//initialize sub-controls
this.$element.find( '.selectlist' ).selectlist();
this.$startDate.datepicker( this.options.startDateOptions );
var startDateResponse = ( typeof this.options.startDateChanged === "function" ) ? this.options.startDateChanged : this._guessEndDate;
this.$startDate.on( 'change changed.fu.datepicker dateClicked.fu.datepicker', $.proxy( startDateResponse, this ) );
this.$startTime.combobox();
// init start time
if ( this.$startTime.find( 'input' ).val() === '' ) {
this.$startTime.combobox( 'selectByIndex', 0 );
}
// every 0 days/hours doesn't make sense, change if not set
if ( this.$repeatIntervalSpinbox.find( 'input' ).val() === '0' ) {
this.$repeatIntervalSpinbox.spinbox( {
'value': 1,
'min': 1,
'limitToStep': true
} );
} else {
this.$repeatIntervalSpinbox.spinbox( {
'min': 1,
'limitToStep': true
} );
}
this.$endAfter.spinbox( {
'value': 1,
'min': 1,
'limitToStep': true
} );
this.$endDate.datepicker( this.options.endDateOptions );
this.$element.find( '.radio-custom' ).radio();
// bind events: 'change' is a Bootstrap JS fired event
this.$repeatIntervalSelect.on( 'changed.fu.selectlist', $.proxy( this.repeatIntervalSelectChanged, this ) );
this.$endSelect.on( 'changed.fu.selectlist', $.proxy( this.endSelectChanged, this ) );
this.$element.find( '.repeat-days-of-the-week .btn-group .btn' ).on( 'change.fu.scheduler', function( e, data ) {
self.changed( e, data, true );
} );
this.$element.find( '.combobox' ).on( 'changed.fu.combobox', $.proxy( this.changed, this ) );
this.$element.find( '.datepicker' ).on( 'changed.fu.datepicker', $.proxy( this.changed, this ) );
this.$element.find( '.datepicker' ).on( 'dateClicked.fu.datepicker', $.proxy( this.changed, this ) );
this.$element.find( '.selectlist' ).on( 'changed.fu.selectlist', $.proxy( this.changed, this ) );
this.$element.find( '.spinbox' ).on( 'changed.fu.spinbox', $.proxy( this.changed, this ) );
this.$element.find( '.repeat-monthly .radio-custom, .repeat-yearly .radio-custom' ).on( 'change.fu.scheduler', $.proxy( this.changed, this ) );
}
|
setValue() sets the Placard triggering DOM element's display value
@param {String} the value to be displayed
@param {Boolean} If you want to explicitly suppress the application
of ellipsis, pass `true`. This would typically only be
done from internal functions (like `applyEllipsis`)
that want to avoid circular logic. Otherwise, the
value of the option applyEllipsis will be used.
@return {Object} jQuery object representing the DOM element whose
value was set
|
Scheduler
|
javascript
|
ExactTarget/fuelux
|
reference/dist/js/fuelux.js
|
https://github.com/ExactTarget/fuelux/blob/master/reference/dist/js/fuelux.js
|
BSD-3-Clause
|
_getFormattedDate = function _getFormattedDate( dateObj, dash ) {
var fdate = '';
var item;
fdate += dateObj.getFullYear();
fdate += dash;
item = dateObj.getMonth() + 1; //because 0 indexing makes sense when dealing with months /sarcasm
fdate += ( item < 10 ) ? '0' + item : item;
fdate += dash;
item = dateObj.getDate();
fdate += ( item < 10 ) ? '0' + item : item;
return fdate;
}
|
setValue() sets the Placard triggering DOM element's display value
@param {String} the value to be displayed
@param {Boolean} If you want to explicitly suppress the application
of ellipsis, pass `true`. This would typically only be
done from internal functions (like `applyEllipsis`)
that want to avoid circular logic. Otherwise, the
value of the option applyEllipsis will be used.
@return {Object} jQuery object representing the DOM element whose
value was set
|
_getFormattedDate
|
javascript
|
ExactTarget/fuelux
|
reference/dist/js/fuelux.js
|
https://github.com/ExactTarget/fuelux/blob/master/reference/dist/js/fuelux.js
|
BSD-3-Clause
|
_incrementDate = function _incrementDate( start, end, interval, increment ) {
return new Date( start.getTime() + ( INTERVALS[ interval ] * increment ) );
}
|
setValue() sets the Placard triggering DOM element's display value
@param {String} the value to be displayed
@param {Boolean} If you want to explicitly suppress the application
of ellipsis, pass `true`. This would typically only be
done from internal functions (like `applyEllipsis`)
that want to avoid circular logic. Otherwise, the
value of the option applyEllipsis will be used.
@return {Object} jQuery object representing the DOM element whose
value was set
|
_incrementDate
|
javascript
|
ExactTarget/fuelux
|
reference/dist/js/fuelux.js
|
https://github.com/ExactTarget/fuelux/blob/master/reference/dist/js/fuelux.js
|
BSD-3-Clause
|
function z( n ) {
return ( n < 10 ? '0' : '' ) + n;
}
|
setValue() sets the Placard triggering DOM element's display value
@param {String} the value to be displayed
@param {Boolean} If you want to explicitly suppress the application
of ellipsis, pass `true`. This would typically only be
done from internal functions (like `applyEllipsis`)
that want to avoid circular logic. Otherwise, the
value of the option applyEllipsis will be used.
@return {Object} jQuery object representing the DOM element whose
value was set
|
z
|
javascript
|
ExactTarget/fuelux
|
reference/dist/js/fuelux.js
|
https://github.com/ExactTarget/fuelux/blob/master/reference/dist/js/fuelux.js
|
BSD-3-Clause
|
Picker = function Picker( element, options ) {
var self = this;
this.$element = $( element );
this.options = $.extend( {}, $.fn.picker.defaults, options );
this.$accept = this.$element.find( '.picker-accept' );
this.$cancel = this.$element.find( '.picker-cancel' );
this.$trigger = this.$element.find( '.picker-trigger' );
this.$footer = this.$element.find( '.picker-footer' );
this.$header = this.$element.find( '.picker-header' );
this.$popup = this.$element.find( '.picker-popup' );
this.$body = this.$element.find( '.picker-body' );
this.clickStamp = '_';
this.isInput = this.$trigger.is( 'input' );
this.$trigger.on( 'keydown.fu.picker', $.proxy( this.keyComplete, this ) );
this.$trigger.on( 'focus.fu.picker', $.proxy( function inputFocus( e ) {
if ( typeof e === "undefined" || $( e.target ).is( 'input[type=text]' ) ) {
$.proxy( this.show(), this );
}
}, this ) );
this.$trigger.on( 'click.fu.picker', $.proxy( function triggerClick( e ) {
if ( !$( e.target ).is( 'input[type=text]' ) ) {
$.proxy( this.toggle(), this );
} else {
$.proxy( this.show(), this );
}
}, this ) );
this.$accept.on( 'click.fu.picker', $.proxy( this.complete, this, 'accepted' ) );
this.$cancel.on( 'click.fu.picker', function( e ) {
e.preventDefault();
self.complete( 'cancelled' );
} );
}
|
setValue() sets the Placard triggering DOM element's display value
@param {String} the value to be displayed
@param {Boolean} If you want to explicitly suppress the application
of ellipsis, pass `true`. This would typically only be
done from internal functions (like `applyEllipsis`)
that want to avoid circular logic. Otherwise, the
value of the option applyEllipsis will be used.
@return {Object} jQuery object representing the DOM element whose
value was set
|
Picker
|
javascript
|
ExactTarget/fuelux
|
reference/dist/js/fuelux.js
|
https://github.com/ExactTarget/fuelux/blob/master/reference/dist/js/fuelux.js
|
BSD-3-Clause
|
_isOffscreen = function _isOffscreen( picker ) {
var windowHeight = Math.max( document.documentElement.clientHeight, window.innerHeight || 0 );
var scrollTop = $( document ).scrollTop();
var popupTop = picker.$popup.offset();
var popupBottom = popupTop.top + picker.$popup.outerHeight( true );
//if the bottom of the popup goes off the page, but the top does not, dropup.
if ( popupBottom > windowHeight + scrollTop || popupTop.top < scrollTop ) {
return true;
} else { //otherwise, prefer showing the top of the popup only vs the bottom
return false;
}
}
|
setValue() sets the Placard triggering DOM element's display value
@param {String} the value to be displayed
@param {Boolean} If you want to explicitly suppress the application
of ellipsis, pass `true`. This would typically only be
done from internal functions (like `applyEllipsis`)
that want to avoid circular logic. Otherwise, the
value of the option applyEllipsis will be used.
@return {Object} jQuery object representing the DOM element whose
value was set
|
_isOffscreen
|
javascript
|
ExactTarget/fuelux
|
reference/dist/js/fuelux.js
|
https://github.com/ExactTarget/fuelux/blob/master/reference/dist/js/fuelux.js
|
BSD-3-Clause
|
_display = function _display( picker ) {
picker.$popup.css( 'visibility', 'hidden' );
_showBelow( picker );
//if part of the popup is offscreen try to show it above
if ( _isOffscreen( picker ) ) {
_showAbove( picker );
//if part of the popup is still offscreen, prefer cutting off the bottom
if ( _isOffscreen( picker ) ) {
_showBelow( picker );
}
}
picker.$popup.css( 'visibility', 'visible' );
}
|
setValue() sets the Placard triggering DOM element's display value
@param {String} the value to be displayed
@param {Boolean} If you want to explicitly suppress the application
of ellipsis, pass `true`. This would typically only be
done from internal functions (like `applyEllipsis`)
that want to avoid circular logic. Otherwise, the
value of the option applyEllipsis will be used.
@return {Object} jQuery object representing the DOM element whose
value was set
|
_display
|
javascript
|
ExactTarget/fuelux
|
reference/dist/js/fuelux.js
|
https://github.com/ExactTarget/fuelux/blob/master/reference/dist/js/fuelux.js
|
BSD-3-Clause
|
_showAbove = function _showAbove( picker ) {
picker.$popup.css( 'top', -picker.$popup.outerHeight( true ) + 'px' );
}
|
setValue() sets the Placard triggering DOM element's display value
@param {String} the value to be displayed
@param {Boolean} If you want to explicitly suppress the application
of ellipsis, pass `true`. This would typically only be
done from internal functions (like `applyEllipsis`)
that want to avoid circular logic. Otherwise, the
value of the option applyEllipsis will be used.
@return {Object} jQuery object representing the DOM element whose
value was set
|
_showAbove
|
javascript
|
ExactTarget/fuelux
|
reference/dist/js/fuelux.js
|
https://github.com/ExactTarget/fuelux/blob/master/reference/dist/js/fuelux.js
|
BSD-3-Clause
|
_showBelow = function _showBelow( picker ) {
picker.$popup.css( 'top', picker.$trigger.outerHeight( true ) + 'px' );
}
|
setValue() sets the Placard triggering DOM element's display value
@param {String} the value to be displayed
@param {Boolean} If you want to explicitly suppress the application
of ellipsis, pass `true`. This would typically only be
done from internal functions (like `applyEllipsis`)
that want to avoid circular logic. Otherwise, the
value of the option applyEllipsis will be used.
@return {Object} jQuery object representing the DOM element whose
value was set
|
_showBelow
|
javascript
|
ExactTarget/fuelux
|
reference/dist/js/fuelux.js
|
https://github.com/ExactTarget/fuelux/blob/master/reference/dist/js/fuelux.js
|
BSD-3-Clause
|
function _create(data, format, datatype) {
// get storage format constructor
var M = type.Matrix.storage(format || 'default'); // create instance
return new M(data, datatype);
}
|
Create a new Matrix with given storage format
@param {Array} data
@param {string} [format]
@param {string} [datatype]
@returns {Matrix} Returns a new Matrix
@private
|
_create
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function size(x) {
var s = [];
while (Array.isArray(x)) {
s.push(x.length);
x = x[0];
}
return s;
}
|
Calculate the size of a multi dimensional array.
This function checks the size of the first entry, it does not validate
whether all dimensions match. (use function `validate` for that)
@param {Array} x
@Return {Number[]} size
|
size
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _validate(array, size, dim) {
var i;
var len = array.length;
if (len !== size[dim]) {
throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_2___default.a(len, size[dim]);
}
if (dim < size.length - 1) {
// recursively validate each child array
var dimNext = dim + 1;
for (i = 0; i < len; i++) {
var child = array[i];
if (!Array.isArray(child)) {
throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_2___default.a(size.length - 1, size.length, '<');
}
_validate(array[i], size, dimNext);
}
} else {
// last dimension. none of the childs may be an array
for (i = 0; i < len; i++) {
if (Array.isArray(array[i])) {
throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_2___default.a(size.length + 1, size.length, '>');
}
}
}
}
|
Recursively validate whether each element in a multi dimensional array
has a size corresponding to the provided size array.
@param {Array} array Array to be validated
@param {number[]} size Array with the size of each dimension
@param {number} dim Current dimension
@throws DimensionError
@private
|
_validate
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function validate(array, size) {
var isScalar = size.length === 0;
if (isScalar) {
// scalar
if (Array.isArray(array)) {
throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_2___default.a(array.length, 0);
}
} else {
// array
_validate(array, size, 0);
}
}
|
Validate whether each element in a multi dimensional array has
a size corresponding to the provided size array.
@param {Array} array Array to be validated
@param {number[]} size Array with the size of each dimension
@throws DimensionError
|
validate
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function validateIndex(index, length) {
if (!_number__WEBPACK_IMPORTED_MODULE_0___default.a.isNumber(index) || !_number__WEBPACK_IMPORTED_MODULE_0___default.a.isInteger(index)) {
throw new TypeError('Index must be an integer (value: ' + index + ')');
}
if (index < 0 || typeof length === 'number' && index >= length) {
throw new _error_IndexError__WEBPACK_IMPORTED_MODULE_3___default.a(index, length);
}
}
|
Test whether index is an integer number with index >= 0 and index < length
when length is provided
@param {number} index Zero-based index
@param {number} [length] Length of the array
|
validateIndex
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function resize(array, size, defaultValue) {
// TODO: add support for scalars, having size=[] ?
// check the type of the arguments
if (!Array.isArray(array) || !Array.isArray(size)) {
throw new TypeError('Array expected');
}
if (size.length === 0) {
throw new Error('Resizing to scalar is not supported');
} // check whether size contains positive integers
size.forEach(function (value) {
if (!_number__WEBPACK_IMPORTED_MODULE_0___default.a.isNumber(value) || !_number__WEBPACK_IMPORTED_MODULE_0___default.a.isInteger(value) || value < 0) {
throw new TypeError('Invalid size, must contain positive integers ' + '(size: ' + _string__WEBPACK_IMPORTED_MODULE_1___default.a.format(size) + ')');
}
}); // recursively resize the array
var _defaultValue = defaultValue !== undefined ? defaultValue : 0;
_resize(array, size, 0, _defaultValue);
return array;
}
|
Resize a multi dimensional array. The resized array is returned.
@param {Array} array Array to be resized
@param {Array.<number>} size Array with the size of each dimension
@param {*} [defaultValue=0] Value to be filled in in new entries,
zero by default. Specify for example `null`,
to clearly see entries that are not explicitly
set.
@return {Array} array The resized array
|
resize
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _resize(array, size, dim, defaultValue) {
var i;
var elem;
var oldLen = array.length;
var newLen = size[dim];
var minLen = Math.min(oldLen, newLen); // apply new length
array.length = newLen;
if (dim < size.length - 1) {
// non-last dimension
var dimNext = dim + 1; // resize existing child arrays
for (i = 0; i < minLen; i++) {
// resize child array
elem = array[i];
if (!Array.isArray(elem)) {
elem = [elem]; // add a dimension
array[i] = elem;
}
_resize(elem, size, dimNext, defaultValue);
} // create new child arrays
for (i = minLen; i < newLen; i++) {
// get child array
elem = [];
array[i] = elem; // resize new child array
_resize(elem, size, dimNext, defaultValue);
}
} else {
// last dimension
// remove dimensions of existing values
for (i = 0; i < minLen; i++) {
while (Array.isArray(array[i])) {
array[i] = array[i][0];
}
} // fill new elements with the default value
for (i = minLen; i < newLen; i++) {
array[i] = defaultValue;
}
}
}
|
Recursively resize a multi dimensional array
@param {Array} array Array to be resized
@param {number[]} size Array with the size of each dimension
@param {number} dim Current dimension
@param {*} [defaultValue] Value to be filled in in new entries,
undefined by default.
@private
|
_resize
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function reshape(array, sizes) {
var flatArray = flatten(array);
var newArray;
function product(arr) {
return arr.reduce(function (prev, curr) {
return prev * curr;
});
}
if (!Array.isArray(array) || !Array.isArray(sizes)) {
throw new TypeError('Array expected');
}
if (sizes.length === 0) {
throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_2___default.a(0, product(size(array)), '!=');
}
var totalSize = 1;
for (var sizeIndex = 0; sizeIndex < sizes.length; sizeIndex++) {
totalSize *= sizes[sizeIndex];
}
if (flatArray.length !== totalSize) {
throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_2___default.a(product(sizes), product(size(array)), '!=');
}
try {
newArray = _reshape(flatArray, sizes);
} catch (e) {
if (e instanceof _error_DimensionError__WEBPACK_IMPORTED_MODULE_2___default.a) {
throw new _error_DimensionError__WEBPACK_IMPORTED_MODULE_2___default.a(product(sizes), product(size(array)), '!=');
}
throw e;
}
return newArray;
}
|
Re-shape a multi dimensional array to fit the specified dimensions
@param {Array} array Array to be reshaped
@param {Array.<number>} sizes List of sizes for each dimension
@returns {Array} Array whose data has been formatted to fit the
specified dimensions
@throws {DimensionError} If the product of the new dimension sizes does
not equal that of the old ones
|
reshape
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function product(arr) {
return arr.reduce(function (prev, curr) {
return prev * curr;
});
}
|
Re-shape a multi dimensional array to fit the specified dimensions
@param {Array} array Array to be reshaped
@param {Array.<number>} sizes List of sizes for each dimension
@returns {Array} Array whose data has been formatted to fit the
specified dimensions
@throws {DimensionError} If the product of the new dimension sizes does
not equal that of the old ones
|
product
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _reshape(array, sizes) {
// testing if there are enough elements for the requested shape
var tmpArray = array;
var tmpArray2; // for each dimensions starting by the last one and ignoring the first one
for (var sizeIndex = sizes.length - 1; sizeIndex > 0; sizeIndex--) {
var size = sizes[sizeIndex];
tmpArray2 = []; // aggregate the elements of the current tmpArray in elements of the requested size
var length = tmpArray.length / size;
for (var i = 0; i < length; i++) {
tmpArray2.push(tmpArray.slice(i * size, (i + 1) * size));
} // set it as the new tmpArray for the next loop turn or for return
tmpArray = tmpArray2;
}
return tmpArray;
}
|
Iteratively re-shape a multi dimensional array to fit the specified dimensions
@param {Array} array Array to be reshaped
@param {Array.<number>} sizes List of sizes for each dimension
@returns {Array} Array whose data has been formatted to fit the
specified dimensions
|
_reshape
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function squeeze(array, arraySize) {
var s = arraySize || size(array); // squeeze outer dimensions
while (Array.isArray(array) && array.length === 1) {
array = array[0];
s.shift();
} // find the first dimension to be squeezed
var dims = s.length;
while (s[dims - 1] === 1) {
dims--;
} // squeeze inner dimensions
if (dims < s.length) {
array = _squeeze(array, dims, 0);
s.length = dims;
}
return array;
}
|
Squeeze a multi dimensional array
@param {Array} array
@param {Array} [arraySize]
@returns {Array} returns the array itself
|
squeeze
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _squeeze(array, dims, dim) {
var i, ii;
if (dim < dims) {
var next = dim + 1;
for (i = 0, ii = array.length; i < ii; i++) {
array[i] = _squeeze(array[i], dims, next);
}
} else {
while (Array.isArray(array)) {
array = array[0];
}
}
return array;
}
|
Recursively squeeze a multi dimensional array
@param {Array} array
@param {number} dims Required number of dimensions
@param {number} dim Current dimension
@returns {Array | *} Returns the squeezed array
@private
|
_squeeze
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function unsqueeze(array, dims, outer, arraySize) {
var s = arraySize || size(array); // unsqueeze outer dimensions
if (outer) {
for (var i = 0; i < outer; i++) {
array = [array];
s.unshift(1);
}
} // unsqueeze inner dimensions
array = _unsqueeze(array, dims, 0);
while (s.length < dims) {
s.push(1);
}
return array;
}
|
Unsqueeze a multi dimensional array: add dimensions when missing
Paramter `size` will be mutated to match the new, unqueezed matrix size.
@param {Array} array
@param {number} dims Desired number of dimensions of the array
@param {number} [outer] Number of outer dimensions to be added
@param {Array} [arraySize] Current size of array.
@returns {Array} returns the array itself
@private
|
unsqueeze
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _unsqueeze(array, dims, dim) {
var i, ii;
if (Array.isArray(array)) {
var next = dim + 1;
for (i = 0, ii = array.length; i < ii; i++) {
array[i] = _unsqueeze(array[i], dims, next);
}
} else {
for (var d = dim; d < dims; d++) {
array = [array];
}
}
return array;
}
|
Recursively unsqueeze a multi dimensional array
@param {Array} array
@param {number} dims Required number of dimensions
@param {number} dim Current dimension
@returns {Array | *} Returns the squeezed array
@private
|
_unsqueeze
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function flatten(array) {
if (!Array.isArray(array)) {
// if not an array, return as is
return array;
}
var flat = [];
array.forEach(function callback(value) {
if (Array.isArray(value)) {
value.forEach(callback); // traverse through sub-arrays recursively
} else {
flat.push(value);
}
});
return flat;
}
|
Flatten a multi dimensional array, put all elements in a one dimensional
array
@param {Array} array A multi dimensional array
@return {Array} The flattened array (1 dimensional)
|
flatten
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function map(array, callback) {
return Array.prototype.map.call(array, callback);
}
|
A safe map
@param {Array} array
@param {function} callback
|
map
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function forEach(array, callback) {
Array.prototype.forEach.call(array, callback);
}
|
A safe forEach
@param {Array} array
@param {function} callback
|
forEach
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function filter(array, callback) {
if (size(array).length !== 1) {
throw new Error('Only one dimensional matrices supported');
}
return Array.prototype.filter.call(array, callback);
}
|
A safe filter
@param {Array} array
@param {function} callback
|
filter
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function filterRegExp(array, regexp) {
if (size(array).length !== 1) {
throw new Error('Only one dimensional matrices supported');
}
return Array.prototype.filter.call(array, function (entry) {
return regexp.test(entry);
});
}
|
Filter values in a callback given a regular expression
@param {Array} array
@param {RegExp} regexp
@return {Array} Returns the filtered array
@private
|
filterRegExp
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function join(array, separator) {
return Array.prototype.join.call(array, separator);
}
|
A safe join
@param {Array} array
@param {string} separator
|
join
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function identify(a) {
if (!Array.isArray(a)) {
throw new TypeError('Array input expected');
}
if (a.length === 0) {
return a;
}
var b = [];
var count = 0;
b[0] = {
value: a[0],
identifier: 0
};
for (var i = 1; i < a.length; i++) {
if (a[i] === a[i - 1]) {
count++;
} else {
count = 0;
}
b.push({
value: a[i],
identifier: count
});
}
return b;
}
|
Assign a numeric identifier to every element of a sorted array
@param {Array} a An array
@return {Array} An array of objects containing the original value and its identifier
|
identify
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function generalize(a) {
if (!Array.isArray(a)) {
throw new TypeError('Array input expected');
}
if (a.length === 0) {
return a;
}
var b = [];
for (var i = 0; i < a.length; i++) {
b.push(a[i].value);
}
return b;
}
|
Remove the numeric identifier from the elements
@param {array} a An array
@return {array} An array of values without identifiers
|
generalize
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function zeros(length) {
var arr = [];
for (var i = 0; i < length; i++) {
arr.push(0);
}
return arr;
}
|
Create an array filled with zeros.
@param {number} length
@return {Array}
|
zeros
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
algorithm14 = function algorithm14(a, b, callback, inverse) {
// a arrays
var adata = a._data;
var asize = a._size;
var adt = a._datatype; // datatype
var dt; // callback signature to use
var cf = callback; // process data types
if (typeof adt === 'string') {
// datatype
dt = adt; // convert b to the same datatype
b = typed.convert(b, dt); // callback
cf = typed.find(callback, [dt, dt]);
} // populate cdata, iterate through dimensions
var cdata = asize.length > 0 ? _iterate(cf, 0, asize, asize[0], adata, b, inverse) : []; // c matrix
return new DenseMatrix({
data: cdata,
size: clone(asize),
datatype: dt
});
}
|
Iterates over DenseMatrix items and invokes the callback function f(Aij..z, b).
Callback function invoked MxN times.
C(i,j,...z) = f(Aij..z, b)
@param {Matrix} a The DenseMatrix instance (A)
@param {Scalar} b The Scalar value
@param {Function} callback The f(Aij..z,b) operation to invoke
@param {boolean} inverse A true value indicates callback should be invoked f(b,Aij..z)
@return {Matrix} DenseMatrix (C)
https://github.com/josdejong/mathjs/pull/346#issuecomment-97659042
|
algorithm14
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _iterate(f, level, s, n, av, bv, inverse) {
// initialize array for this level
var cv = []; // check we reach the last level
if (level === s.length - 1) {
// loop arrays in last level
for (var i = 0; i < n; i++) {
// invoke callback and store value
cv[i] = inverse ? f(bv, av[i]) : f(av[i], bv);
}
} else {
// iterate current level
for (var j = 0; j < n; j++) {
// iterate next level
cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv, inverse);
}
}
return cv;
}
|
Iterates over DenseMatrix items and invokes the callback function f(Aij..z, b).
Callback function invoked MxN times.
C(i,j,...z) = f(Aij..z, b)
@param {Matrix} a The DenseMatrix instance (A)
@param {Scalar} b The Scalar value
@param {Function} callback The f(Aij..z,b) operation to invoke
@param {boolean} inverse A true value indicates callback should be invoked f(b,Aij..z)
@return {Matrix} DenseMatrix (C)
https://github.com/josdejong/mathjs/pull/346#issuecomment-97659042
|
_iterate
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
algorithm13 = function algorithm13(a, b, callback) {
// a arrays
var adata = a._data;
var asize = a._size;
var adt = a._datatype; // b arrays
var bdata = b._data;
var bsize = b._size;
var bdt = b._datatype; // c arrays
var csize = []; // validate dimensions
if (asize.length !== bsize.length) {
throw new DimensionError(asize.length, bsize.length);
} // validate each one of the dimension sizes
for (var s = 0; s < asize.length; s++) {
// must match
if (asize[s] !== bsize[s]) {
throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
} // update dimension in c
csize[s] = asize[s];
} // datatype
var dt; // callback signature to use
var cf = callback; // process data types
if (typeof adt === 'string' && adt === bdt) {
// datatype
dt = adt; // callback
cf = typed.find(callback, [dt, dt]);
} // populate cdata, iterate through dimensions
var cdata = csize.length > 0 ? _iterate(cf, 0, csize, csize[0], adata, bdata) : []; // c matrix
return new DenseMatrix({
data: cdata,
size: csize,
datatype: dt
});
}
|
Iterates over DenseMatrix items and invokes the callback function f(Aij..z, Bij..z).
Callback function invoked MxN times.
C(i,j,...z) = f(Aij..z, Bij..z)
@param {Matrix} a The DenseMatrix instance (A)
@param {Matrix} b The DenseMatrix instance (B)
@param {Function} callback The f(Aij..z,Bij..z) operation to invoke
@return {Matrix} DenseMatrix (C)
https://github.com/josdejong/mathjs/pull/346#issuecomment-97658658
|
algorithm13
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _iterate(f, level, s, n, av, bv) {
// initialize array for this level
var cv = []; // check we reach the last level
if (level === s.length - 1) {
// loop arrays in last level
for (var i = 0; i < n; i++) {
// invoke callback and store value
cv[i] = f(av[i], bv[i]);
}
} else {
// iterate current level
for (var j = 0; j < n; j++) {
// iterate next level
cv[j] = _iterate(f, level + 1, s, s[level + 1], av[j], bv[j]);
}
}
return cv;
}
|
Iterates over DenseMatrix items and invokes the callback function f(Aij..z, Bij..z).
Callback function invoked MxN times.
C(i,j,...z) = f(Aij..z, Bij..z)
@param {Matrix} a The DenseMatrix instance (A)
@param {Matrix} b The DenseMatrix instance (B)
@param {Function} callback The f(Aij..z,Bij..z) operation to invoke
@return {Matrix} DenseMatrix (C)
https://github.com/josdejong/mathjs/pull/346#issuecomment-97658658
|
_iterate
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function DimensionError(actual, expected, relation) {
if (!(this instanceof DimensionError)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this.actual = actual;
this.expected = expected;
this.relation = relation;
this.message = 'Dimension mismatch (' + (Array.isArray(actual) ? '[' + actual.join(', ') + ']' : actual) + ' ' + (this.relation || '!=') + ' ' + (Array.isArray(expected) ? '[' + expected.join(', ') + ']' : expected) + ')';
this.stack = new Error().stack;
}
|
Create a range error with the message:
'Dimension mismatch (<actual size> != <expected size>)'
@param {number | number[]} actual The actual size
@param {number | number[]} expected The expected size
@param {string} [relation='!='] Optional relation between actual
and expected size: '!=', '<', etc.
@extends RangeError
|
DimensionError
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function formatArray(array, options) {
if (Array.isArray(array)) {
var str = '[';
var len = array.length;
for (var i = 0; i < len; i++) {
if (i !== 0) {
str += ', ';
}
str += formatArray(array[i], options);
}
str += ']';
return str;
} else {
return exports.format(array, options);
}
}
|
Recursively format an n-dimensional matrix
Example output: "[[1, 2], [3, 4]]"
@param {Array} array
@param {Object | number | Function} [options] Formatting options. See
lib/utils/number:format for a
description of the available
options.
@returns {string} str
|
formatArray
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function looksLikeFraction(value) {
return value && _typeof(value) === 'object' && typeof value.s === 'number' && typeof value.n === 'number' && typeof value.d === 'number' || false;
}
|
Check whether a value looks like a Fraction (unsafe duck-type check)
@param {*} value
@return {boolean}
|
looksLikeFraction
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _validateMatrixDimensions(size1, size2) {
// check left operand dimensions
switch (size1.length) {
case 1:
// check size2
switch (size2.length) {
case 1:
// Vector x Vector
if (size1[0] !== size2[0]) {
// throw error
throw new RangeError('Dimension mismatch in multiplication. Vectors must have the same length');
}
break;
case 2:
// Vector x Matrix
if (size1[0] !== size2[0]) {
// throw error
throw new RangeError('Dimension mismatch in multiplication. Vector length (' + size1[0] + ') must match Matrix rows (' + size2[0] + ')');
}
break;
default:
throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)');
}
break;
case 2:
// check size2
switch (size2.length) {
case 1:
// Matrix x Vector
if (size1[1] !== size2[0]) {
// throw error
throw new RangeError('Dimension mismatch in multiplication. Matrix columns (' + size1[1] + ') must match Vector length (' + size2[0] + ')');
}
break;
case 2:
// Matrix x Matrix
if (size1[1] !== size2[0]) {
// throw error
throw new RangeError('Dimension mismatch in multiplication. Matrix A columns (' + size1[1] + ') must match Matrix B rows (' + size2[0] + ')');
}
break;
default:
throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix B has ' + size2.length + ' dimensions)');
}
break;
default:
throw new Error('Can only multiply a 1 or 2 dimensional matrix (Matrix A has ' + size1.length + ' dimensions)');
}
}
|
Multiply two or more values, `x * y`.
For matrices, the matrix product is calculated.
Syntax:
math.multiply(x, y)
math.multiply(x, y, z, ...)
Examples:
math.multiply(4, 5.2) // returns number 20.8
math.multiply(2, 3, 4) // returns number 24
const a = math.complex(2, 3)
const b = math.complex(4, 1)
math.multiply(a, b) // returns Complex 5 + 14i
const c = [[1, 2], [4, 3]]
const d = [[1, 2, 3], [3, -4, 7]]
math.multiply(c, d) // returns Array [[7, -6, 17], [13, -4, 33]]
const e = math.unit('2.1 km')
math.multiply(3, e) // returns Unit 6.3 km
See also:
divide, prod, cross, dot
@param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} x First value to multiply
@param {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} y Second value to multiply
@return {number | BigNumber | Fraction | Complex | Unit | Array | Matrix} Multiplication of `x` and `y`
|
_validateMatrixDimensions
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _multiplyVectorVector(a, b, n) {
// check empty vector
if (n === 0) {
throw new Error('Cannot multiply two empty vectors');
} // a dense
var adata = a._data;
var adt = a._datatype; // b dense
var bdata = b._data;
var bdt = b._datatype; // datatype
var dt; // addScalar signature to use
var af = addScalar; // multiplyScalar signature to use
var mf = multiplyScalar; // process data types
if (adt && bdt && adt === bdt && typeof adt === 'string') {
// datatype
dt = adt; // find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
} // result (do not initialize it with zero)
var c = mf(adata[0], bdata[0]); // loop data
for (var i = 1; i < n; i++) {
// multiply and accumulate
c = af(c, mf(adata[i], bdata[i]));
}
return c;
}
|
C = A * B
@param {Matrix} a Dense Vector (N)
@param {Matrix} b Dense Vector (N)
@return {number} Scalar value
|
_multiplyVectorVector
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _multiplyVectorMatrix(a, b) {
// process storage
if (b.storage() !== 'dense') {
throw new Error('Support for SparseMatrix not implemented');
}
return _multiplyVectorDenseMatrix(a, b);
}
|
C = A * B
@param {Matrix} a Dense Vector (M)
@param {Matrix} b Matrix (MxN)
@return {Matrix} Dense Vector (N)
|
_multiplyVectorMatrix
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _multiplyVectorDenseMatrix(a, b) {
// a dense
var adata = a._data;
var asize = a._size;
var adt = a._datatype; // b dense
var bdata = b._data;
var bsize = b._size;
var bdt = b._datatype; // rows & columns
var alength = asize[0];
var bcolumns = bsize[1]; // datatype
var dt; // addScalar signature to use
var af = addScalar; // multiplyScalar signature to use
var mf = multiplyScalar; // process data types
if (adt && bdt && adt === bdt && typeof adt === 'string') {
// datatype
dt = adt; // find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
} // result
var c = []; // loop matrix columns
for (var j = 0; j < bcolumns; j++) {
// sum (do not initialize it with zero)
var sum = mf(adata[0], bdata[0][j]); // loop vector
for (var i = 1; i < alength; i++) {
// multiply & accumulate
sum = af(sum, mf(adata[i], bdata[i][j]));
}
c[j] = sum;
} // return matrix
return new DenseMatrix({
data: c,
size: [bcolumns],
datatype: dt
});
}
|
C = A * B
@param {Matrix} a Dense Vector (M)
@param {Matrix} b Dense Matrix (MxN)
@return {Matrix} Dense Vector (N)
|
_multiplyVectorDenseMatrix
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _multiplyDenseMatrixVector(a, b) {
// a dense
var adata = a._data;
var asize = a._size;
var adt = a._datatype; // b dense
var bdata = b._data;
var bdt = b._datatype; // rows & columns
var arows = asize[0];
var acolumns = asize[1]; // datatype
var dt; // addScalar signature to use
var af = addScalar; // multiplyScalar signature to use
var mf = multiplyScalar; // process data types
if (adt && bdt && adt === bdt && typeof adt === 'string') {
// datatype
dt = adt; // find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
} // result
var c = []; // loop matrix a rows
for (var i = 0; i < arows; i++) {
// current row
var row = adata[i]; // sum (do not initialize it with zero)
var sum = mf(row[0], bdata[0]); // loop matrix a columns
for (var j = 1; j < acolumns; j++) {
// multiply & accumulate
sum = af(sum, mf(row[j], bdata[j]));
}
c[i] = sum;
} // return matrix
return new DenseMatrix({
data: c,
size: [arows],
datatype: dt
});
}
|
C = A * B
@param {Matrix} a DenseMatrix (MxN)
@param {Matrix} b Dense Vector (N)
@return {Matrix} Dense Vector (M)
|
_multiplyDenseMatrixVector
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _multiplyDenseMatrixDenseMatrix(a, b) {
// a dense
var adata = a._data;
var asize = a._size;
var adt = a._datatype; // b dense
var bdata = b._data;
var bsize = b._size;
var bdt = b._datatype; // rows & columns
var arows = asize[0];
var acolumns = asize[1];
var bcolumns = bsize[1]; // datatype
var dt; // addScalar signature to use
var af = addScalar; // multiplyScalar signature to use
var mf = multiplyScalar; // process data types
if (adt && bdt && adt === bdt && typeof adt === 'string') {
// datatype
dt = adt; // find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
} // result
var c = []; // loop matrix a rows
for (var i = 0; i < arows; i++) {
// current row
var row = adata[i]; // initialize row array
c[i] = []; // loop matrix b columns
for (var j = 0; j < bcolumns; j++) {
// sum (avoid initializing sum to zero)
var sum = mf(row[0], bdata[0][j]); // loop matrix a columns
for (var x = 1; x < acolumns; x++) {
// multiply & accumulate
sum = af(sum, mf(row[x], bdata[x][j]));
}
c[i][j] = sum;
}
} // return matrix
return new DenseMatrix({
data: c,
size: [arows, bcolumns],
datatype: dt
});
}
|
C = A * B
@param {Matrix} a DenseMatrix (MxN)
@param {Matrix} b DenseMatrix (NxC)
@return {Matrix} DenseMatrix (MxC)
|
_multiplyDenseMatrixDenseMatrix
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _multiplyDenseMatrixSparseMatrix(a, b) {
// a dense
var adata = a._data;
var asize = a._size;
var adt = a._datatype; // b sparse
var bvalues = b._values;
var bindex = b._index;
var bptr = b._ptr;
var bsize = b._size;
var bdt = b._datatype; // validate b matrix
if (!bvalues) {
throw new Error('Cannot multiply Dense Matrix times Pattern only Matrix');
} // rows & columns
var arows = asize[0];
var bcolumns = bsize[1]; // datatype
var dt; // addScalar signature to use
var af = addScalar; // multiplyScalar signature to use
var mf = multiplyScalar; // equalScalar signature to use
var eq = equalScalar; // zero value
var zero = 0; // process data types
if (adt && bdt && adt === bdt && typeof adt === 'string') {
// datatype
dt = adt; // find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype
zero = typed.convert(0, dt);
} // result
var cvalues = [];
var cindex = [];
var cptr = []; // c matrix
var c = new SparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [arows, bcolumns],
datatype: dt
}); // loop b columns
for (var jb = 0; jb < bcolumns; jb++) {
// update ptr
cptr[jb] = cindex.length; // indeces in column jb
var kb0 = bptr[jb];
var kb1 = bptr[jb + 1]; // do not process column jb if no data exists
if (kb1 > kb0) {
// last row mark processed
var last = 0; // loop a rows
for (var i = 0; i < arows; i++) {
// column mark
var mark = i + 1; // C[i, jb]
var cij = void 0; // values in b column j
for (var kb = kb0; kb < kb1; kb++) {
// row
var ib = bindex[kb]; // check value has been initialized
if (last !== mark) {
// first value in column jb
cij = mf(adata[i][ib], bvalues[kb]); // update mark
last = mark;
} else {
// accumulate value
cij = af(cij, mf(adata[i][ib], bvalues[kb]));
}
} // check column has been processed and value != 0
if (last === mark && !eq(cij, zero)) {
// push row & value
cindex.push(i);
cvalues.push(cij);
}
}
}
} // update ptr
cptr[bcolumns] = cindex.length; // return sparse matrix
return c;
}
|
C = A * B
@param {Matrix} a DenseMatrix (MxN)
@param {Matrix} b SparseMatrix (NxC)
@return {Matrix} SparseMatrix (MxC)
|
_multiplyDenseMatrixSparseMatrix
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _multiplySparseMatrixVector(a, b) {
// a sparse
var avalues = a._values;
var aindex = a._index;
var aptr = a._ptr;
var adt = a._datatype; // validate a matrix
if (!avalues) {
throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix');
} // b dense
var bdata = b._data;
var bdt = b._datatype; // rows & columns
var arows = a._size[0];
var brows = b._size[0]; // result
var cvalues = [];
var cindex = [];
var cptr = []; // datatype
var dt; // addScalar signature to use
var af = addScalar; // multiplyScalar signature to use
var mf = multiplyScalar; // equalScalar signature to use
var eq = equalScalar; // zero value
var zero = 0; // process data types
if (adt && bdt && adt === bdt && typeof adt === 'string') {
// datatype
dt = adt; // find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype
zero = typed.convert(0, dt);
} // workspace
var x = []; // vector with marks indicating a value x[i] exists in a given column
var w = []; // update ptr
cptr[0] = 0; // rows in b
for (var ib = 0; ib < brows; ib++) {
// b[ib]
var vbi = bdata[ib]; // check b[ib] != 0, avoid loops
if (!eq(vbi, zero)) {
// A values & index in ib column
for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
// a row
var ia = aindex[ka]; // check value exists in current j
if (!w[ia]) {
// ia is new entry in j
w[ia] = true; // add i to pattern of C
cindex.push(ia); // x(ia) = A
x[ia] = mf(vbi, avalues[ka]);
} else {
// i exists in C already
x[ia] = af(x[ia], mf(vbi, avalues[ka]));
}
}
}
} // copy values from x to column jb of c
for (var p1 = cindex.length, p = 0; p < p1; p++) {
// row
var ic = cindex[p]; // copy value
cvalues[p] = x[ic];
} // update ptr
cptr[1] = cindex.length; // return sparse matrix
return new SparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [arows, 1],
datatype: dt
});
}
|
C = A * B
@param {Matrix} a SparseMatrix (MxN)
@param {Matrix} b Dense Vector (N)
@return {Matrix} SparseMatrix (M, 1)
|
_multiplySparseMatrixVector
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _multiplySparseMatrixDenseMatrix(a, b) {
// a sparse
var avalues = a._values;
var aindex = a._index;
var aptr = a._ptr;
var adt = a._datatype; // validate a matrix
if (!avalues) {
throw new Error('Cannot multiply Pattern only Matrix times Dense Matrix');
} // b dense
var bdata = b._data;
var bdt = b._datatype; // rows & columns
var arows = a._size[0];
var brows = b._size[0];
var bcolumns = b._size[1]; // datatype
var dt; // addScalar signature to use
var af = addScalar; // multiplyScalar signature to use
var mf = multiplyScalar; // equalScalar signature to use
var eq = equalScalar; // zero value
var zero = 0; // process data types
if (adt && bdt && adt === bdt && typeof adt === 'string') {
// datatype
dt = adt; // find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
eq = typed.find(equalScalar, [dt, dt]); // convert 0 to the same datatype
zero = typed.convert(0, dt);
} // result
var cvalues = [];
var cindex = [];
var cptr = []; // c matrix
var c = new SparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [arows, bcolumns],
datatype: dt
}); // workspace
var x = []; // vector with marks indicating a value x[i] exists in a given column
var w = []; // loop b columns
for (var jb = 0; jb < bcolumns; jb++) {
// update ptr
cptr[jb] = cindex.length; // mark in workspace for current column
var mark = jb + 1; // rows in jb
for (var ib = 0; ib < brows; ib++) {
// b[ib, jb]
var vbij = bdata[ib][jb]; // check b[ib, jb] != 0, avoid loops
if (!eq(vbij, zero)) {
// A values & index in ib column
for (var ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
// a row
var ia = aindex[ka]; // check value exists in current j
if (w[ia] !== mark) {
// ia is new entry in j
w[ia] = mark; // add i to pattern of C
cindex.push(ia); // x(ia) = A
x[ia] = mf(vbij, avalues[ka]);
} else {
// i exists in C already
x[ia] = af(x[ia], mf(vbij, avalues[ka]));
}
}
}
} // copy values from x to column jb of c
for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) {
// row
var ic = cindex[p]; // copy value
cvalues[p] = x[ic];
}
} // update ptr
cptr[bcolumns] = cindex.length; // return sparse matrix
return c;
}
|
C = A * B
@param {Matrix} a SparseMatrix (MxN)
@param {Matrix} b DenseMatrix (NxC)
@return {Matrix} SparseMatrix (MxC)
|
_multiplySparseMatrixDenseMatrix
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _multiplySparseMatrixSparseMatrix(a, b) {
// a sparse
var avalues = a._values;
var aindex = a._index;
var aptr = a._ptr;
var adt = a._datatype; // b sparse
var bvalues = b._values;
var bindex = b._index;
var bptr = b._ptr;
var bdt = b._datatype; // rows & columns
var arows = a._size[0];
var bcolumns = b._size[1]; // flag indicating both matrices (a & b) contain data
var values = avalues && bvalues; // datatype
var dt; // addScalar signature to use
var af = addScalar; // multiplyScalar signature to use
var mf = multiplyScalar; // process data types
if (adt && bdt && adt === bdt && typeof adt === 'string') {
// datatype
dt = adt; // find signatures that matches (dt, dt)
af = typed.find(addScalar, [dt, dt]);
mf = typed.find(multiplyScalar, [dt, dt]);
} // result
var cvalues = values ? [] : undefined;
var cindex = [];
var cptr = []; // c matrix
var c = new SparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [arows, bcolumns],
datatype: dt
}); // workspace
var x = values ? [] : undefined; // vector with marks indicating a value x[i] exists in a given column
var w = []; // variables
var ka, ka0, ka1, kb, kb0, kb1, ia, ib; // loop b columns
for (var jb = 0; jb < bcolumns; jb++) {
// update ptr
cptr[jb] = cindex.length; // mark in workspace for current column
var mark = jb + 1; // B values & index in j
for (kb0 = bptr[jb], kb1 = bptr[jb + 1], kb = kb0; kb < kb1; kb++) {
// b row
ib = bindex[kb]; // check we need to process values
if (values) {
// loop values in a[:,ib]
for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
// row
ia = aindex[ka]; // check value exists in current j
if (w[ia] !== mark) {
// ia is new entry in j
w[ia] = mark; // add i to pattern of C
cindex.push(ia); // x(ia) = A
x[ia] = mf(bvalues[kb], avalues[ka]);
} else {
// i exists in C already
x[ia] = af(x[ia], mf(bvalues[kb], avalues[ka]));
}
}
} else {
// loop values in a[:,ib]
for (ka0 = aptr[ib], ka1 = aptr[ib + 1], ka = ka0; ka < ka1; ka++) {
// row
ia = aindex[ka]; // check value exists in current j
if (w[ia] !== mark) {
// ia is new entry in j
w[ia] = mark; // add i to pattern of C
cindex.push(ia);
}
}
}
} // check we need to process matrix values (pattern matrix)
if (values) {
// copy values from x to column jb of c
for (var p0 = cptr[jb], p1 = cindex.length, p = p0; p < p1; p++) {
// row
var ic = cindex[p]; // copy value
cvalues[p] = x[ic];
}
}
} // update ptr
cptr[bcolumns] = cindex.length; // return sparse matrix
return c;
}
|
C = A * B
@param {Matrix} a SparseMatrix (MxN)
@param {Matrix} b SparseMatrix (NxC)
@return {Matrix} SparseMatrix (MxC)
|
_multiplySparseMatrixSparseMatrix
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function getSafeProperty(object, prop) {
// only allow getting safe properties of a plain object
if (isPlainObject(object) && isSafeProperty(object, prop)) {
return object[prop];
}
if (typeof object[prop] === 'function' && isSafeMethod(object, prop)) {
throw new Error('Cannot access method "' + prop + '" as a property');
}
throw new Error('No access to property "' + prop + '"');
}
|
Get a property of a plain object
Throws an error in case the object is not a plain object or the
property is not defined on the object itself
@param {Object} object
@param {string} prop
@return {*} Returns the property value when safe
|
getSafeProperty
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function setSafeProperty(object, prop, value) {
// only allow setting safe properties of a plain object
if (isPlainObject(object) && isSafeProperty(object, prop)) {
object[prop] = value;
return value;
}
throw new Error('No access to property "' + prop + '"');
}
|
Set a property on a plain object.
Throws an error in case the object is not a plain object or the
property would override an inherited property like .constructor or .toString
@param {Object} object
@param {string} prop
@param {*} value
@return {*} Returns the value
|
setSafeProperty
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function isSafeProperty(object, prop) {
if (!object || _typeof(object) !== 'object') {
return false;
} // SAFE: whitelisted
// e.g length
if (hasOwnProperty(safeNativeProperties, prop)) {
return true;
} // UNSAFE: inherited from Object prototype
// e.g constructor
if (prop in Object.prototype) {
// 'in' is used instead of hasOwnProperty for nodejs v0.10
// which is inconsistent on root prototypes. It is safe
// here because Object.prototype is a root object
return false;
} // UNSAFE: inherited from Function prototype
// e.g call, apply
if (prop in Function.prototype) {
// 'in' is used instead of hasOwnProperty for nodejs v0.10
// which is inconsistent on root prototypes. It is safe
// here because Function.prototype is a root object
return false;
}
return true;
}
|
Test whether a property is safe to use for an object.
For example .toString and .constructor are not safe
@param {string} prop
@return {boolean} Returns true when safe
|
isSafeProperty
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function validateSafeMethod(object, method) {
if (!isSafeMethod(object, method)) {
throw new Error('No access to method "' + method + '"');
}
}
|
Validate whether a method is safe.
Throws an error when that's not the case.
@param {Object} object
@param {string} method
|
validateSafeMethod
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function isSafeMethod(object, method) {
if (!object || typeof object[method] !== 'function') {
return false;
} // UNSAFE: ghosted
// e.g overridden toString
// Note that IE10 doesn't support __proto__ and we can't do this check there.
if (hasOwnProperty(object, method) && Object.getPrototypeOf && method in Object.getPrototypeOf(object)) {
return false;
} // SAFE: whitelisted
// e.g toString
if (hasOwnProperty(safeNativeMethods, method)) {
return true;
} // UNSAFE: inherited from Object prototype
// e.g constructor
if (method in Object.prototype) {
// 'in' is used instead of hasOwnProperty for nodejs v0.10
// which is inconsistent on root prototypes. It is safe
// here because Object.prototype is a root object
return false;
} // UNSAFE: inherited from Function prototype
// e.g call, apply
if (method in Function.prototype) {
// 'in' is used instead of hasOwnProperty for nodejs v0.10
// which is inconsistent on root prototypes. It is safe
// here because Function.prototype is a root object
return false;
}
return true;
}
|
Check whether a method is safe.
Throws an error when that's not the case (for example for `constructor`).
@param {Object} object
@param {string} method
@return {boolean} Returns true when safe, false otherwise
|
isSafeMethod
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function isPlainObject(object) {
return _typeof(object) === 'object' && object && object.constructor === Object;
}
|
Check whether a method is safe.
Throws an error when that's not the case (for example for `constructor`).
@param {Object} object
@param {string} method
@return {boolean} Returns true when safe, false otherwise
|
isPlainObject
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function checkEqualDimensions(x, y) {
var xsize = x.size();
var ysize = y.size();
if (xsize.length !== ysize.length) {
throw new DimensionError(xsize.length, ysize.length);
}
}
|
Check whether matrix x and y have the same number of dimensions.
Throws a DimensionError when dimensions are not equal
@param {Matrix} x
@param {Matrix} y
|
checkEqualDimensions
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _traverse(node, callback) {
node.forEach(function (child, path, parent) {
callback(child, path, parent);
_traverse(child, callback);
});
}
|
Recursively traverse all nodes in a node tree. Executes given callback for
this node and each of its child nodes.
@param {function(node: Node, path: string, parent: Node)} callback
A callback called for every node in the node tree.
|
_traverse
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _transform(node, callback) {
return node.map(function (child, path, parent) {
var replacement = callback(child, path, parent);
return _transform(replacement, callback);
});
}
|
Recursively transform a node tree via a transform function.
For example, to replace all nodes of type SymbolNode having name 'x' with a
ConstantNode with value 2:
const res = Node.transform(function (node, path, parent) {
if (node && node.isSymbolNode) && (node.name === 'x')) {
return new ConstantNode(2)
}
else {
return node
}
})
@param {function(node: Node, path: string, parent: Node) : Node} callback
A mapping function accepting a node, and returning
a replacement for the node or the original node.
Signature: callback(node: Node, index: string, parent: Node) : Node
@return {Node} Returns the original node or its replacement
|
_transform
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _validateScope(scope) {
for (var symbol in scope) {
if (hasOwnProperty(scope, symbol)) {
if (symbol in keywords) {
throw new Error('Scope contains an illegal symbol, "' + symbol + '" is a reserved keyword');
}
}
}
}
|
Validate the symbol names of a scope.
Throws an error when the scope contains an illegal symbol.
@param {Object} scope
|
_validateScope
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _getSubstring(str, index) {
if (!type.isIndex(index)) {
// TODO: better error message
throw new TypeError('Index expected');
}
if (index.size().length !== 1) {
throw new DimensionError(index.size().length, 1);
} // validate whether the range is out of range
var strLen = str.length;
validateIndex(index.min()[0], strLen);
validateIndex(index.max()[0], strLen);
var range = index.dimension(0);
var substr = '';
range.forEach(function (v) {
substr += str.charAt(v);
});
return substr;
}
|
Retrieve a subset of a string
@param {string} str string from which to get a substring
@param {Index} index An index containing ranges for each dimension
@returns {string} substring
@private
|
_getSubstring
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _setSubstring(str, index, replacement, defaultValue) {
if (!index || index.isIndex !== true) {
// TODO: better error message
throw new TypeError('Index expected');
}
if (index.size().length !== 1) {
throw new DimensionError(index.size().length, 1);
}
if (defaultValue !== undefined) {
if (typeof defaultValue !== 'string' || defaultValue.length !== 1) {
throw new TypeError('Single character expected as defaultValue');
}
} else {
defaultValue = ' ';
}
var range = index.dimension(0);
var len = range.size()[0];
if (len !== replacement.length) {
throw new DimensionError(range.size()[0], replacement.length);
} // validate whether the range is out of range
var strLen = str.length;
validateIndex(index.min()[0]);
validateIndex(index.max()[0]); // copy the string into an array with characters
var chars = [];
for (var i = 0; i < strLen; i++) {
chars[i] = str.charAt(i);
}
range.forEach(function (v, i) {
chars[v] = replacement.charAt(i[0]);
}); // initialize undefined characters with a space
if (chars.length > strLen) {
for (var _i = strLen - 1, _len = chars.length; _i < _len; _i++) {
if (!chars[_i]) {
chars[_i] = defaultValue;
}
}
}
return chars.join('');
}
|
Replace a substring in a string
@param {string} str string to be replaced
@param {Index} index An index containing ranges for each dimension
@param {string} replacement Replacement string
@param {string} [defaultValue] Default value to be uses when resizing
the string. is ' ' by default
@returns {string} result
@private
|
_setSubstring
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _getObjectProperty(object, index) {
if (index.size().length !== 1) {
throw new DimensionError(index.size(), 1);
}
var key = index.dimension(0);
if (typeof key !== 'string') {
throw new TypeError('String expected as index to retrieve an object property');
}
return getSafeProperty(object, key);
}
|
Retrieve a property from an object
@param {Object} object
@param {Index} index
@return {*} Returns the value of the property
@private
|
_getObjectProperty
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _setObjectProperty(object, index, replacement) {
if (index.size().length !== 1) {
throw new DimensionError(index.size(), 1);
}
var key = index.dimension(0);
if (typeof key !== 'string') {
throw new TypeError('String expected as index to retrieve an object property');
} // clone the object, and apply the property to the clone
var updated = clone(object);
setSafeProperty(updated, key, replacement);
return updated;
}
|
Set a property on an object
@param {Object} object
@param {Index} index
@param {*} replacement
@return {*} Returns the updated object
@private
|
_setObjectProperty
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function Index(ranges) {
if (!(this instanceof Index)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this._dimensions = [];
this._isScalar = true;
for (var i = 0, ii = arguments.length; i < ii; i++) {
var arg = arguments[i];
if (type.isRange(arg)) {
this._dimensions.push(arg);
this._isScalar = false;
} else if (Array.isArray(arg) || type.isMatrix(arg)) {
// create matrix
var m = _createImmutableMatrix(arg.valueOf());
this._dimensions.push(m); // size
var size = m.size(); // scalar
if (size.length !== 1 || size[0] !== 1) {
this._isScalar = false;
}
} else if (typeof arg === 'number') {
this._dimensions.push(_createImmutableMatrix([arg]));
} else if (typeof arg === 'string') {
// object property (arguments.count should be 1)
this._dimensions.push(arg);
} else {
throw new TypeError('Dimension must be an Array, Matrix, number, string, or Range');
} // TODO: implement support for wildcard '*'
}
}
|
Create an index. An Index can store ranges and sets for multiple dimensions.
Matrix.get, Matrix.set, and math.subset accept an Index as input.
Usage:
const index = new Index(range1, range2, matrix1, array1, ...)
Where each parameter can be any of:
A number
A string (containing a name of an object property)
An instance of Range
An Array with the Set values
A Matrix with the Set values
The parameters start, end, and step must be integer numbers.
@class Index
@Constructor Index
@param {...*} ranges
|
Index
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
algorithm07 = function algorithm07(a, b, callback) {
// sparse matrix arrays
var asize = a._size;
var adt = a._datatype; // sparse matrix arrays
var bsize = b._size;
var bdt = b._datatype; // validate dimensions
if (asize.length !== bsize.length) {
throw new DimensionError(asize.length, bsize.length);
} // check rows & columns
if (asize[0] !== bsize[0] || asize[1] !== bsize[1]) {
throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
} // rows & columns
var rows = asize[0];
var columns = asize[1]; // datatype
var dt; // zero value
var zero = 0; // callback signature to use
var cf = callback; // process data types
if (typeof adt === 'string' && adt === bdt) {
// datatype
dt = adt; // convert 0 to the same datatype
zero = typed.convert(0, dt); // callback
cf = typed.find(callback, [dt, dt]);
} // vars
var i, j; // result arrays
var cdata = []; // initialize c
for (i = 0; i < rows; i++) {
cdata[i] = [];
} // matrix
var c = new DenseMatrix({
data: cdata,
size: [rows, columns],
datatype: dt
}); // workspaces
var xa = [];
var xb = []; // marks indicating we have a value in x for a given column
var wa = [];
var wb = []; // loop columns
for (j = 0; j < columns; j++) {
// columns mark
var mark = j + 1; // scatter the values of A(:,j) into workspace
_scatter(a, j, wa, xa, mark); // scatter the values of B(:,j) into workspace
_scatter(b, j, wb, xb, mark); // loop rows
for (i = 0; i < rows; i++) {
// matrix values @ i,j
var va = wa[i] === mark ? xa[i] : zero;
var vb = wb[i] === mark ? xb[i] : zero; // invoke callback
cdata[i][j] = cf(va, vb);
}
} // return sparse matrix
return c;
}
|
Iterates over SparseMatrix A and SparseMatrix B items (zero and nonzero) and invokes the callback function f(Aij, Bij).
Callback function invoked MxN times.
C(i,j) = f(Aij, Bij)
@param {Matrix} a The SparseMatrix instance (A)
@param {Matrix} b The SparseMatrix instance (B)
@param {Function} callback The f(Aij,Bij) operation to invoke
@return {Matrix} DenseMatrix (C)
see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
|
algorithm07
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _scatter(m, j, w, x, mark) {
// a arrays
var values = m._values;
var index = m._index;
var ptr = m._ptr; // loop values in column j
for (var k = ptr[j], k1 = ptr[j + 1]; k < k1; k++) {
// row
var i = index[k]; // update workspace
w[i] = mark;
x[i] = values[k];
}
}
|
Iterates over SparseMatrix A and SparseMatrix B items (zero and nonzero) and invokes the callback function f(Aij, Bij).
Callback function invoked MxN times.
C(i,j) = f(Aij, Bij)
@param {Matrix} a The SparseMatrix instance (A)
@param {Matrix} b The SparseMatrix instance (B)
@param {Function} callback The f(Aij,Bij) operation to invoke
@return {Matrix} DenseMatrix (C)
see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
|
_scatter
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function compareMatricesAndArrays(x, y) {
if (type.isSparseMatrix(x) && type.isSparseMatrix(y)) {
return compareArrays(x.toJSON().values, y.toJSON().values);
}
if (type.isSparseMatrix(x)) {
// note: convert to array is expensive
return compareMatricesAndArrays(x.toArray(), y);
}
if (type.isSparseMatrix(y)) {
// note: convert to array is expensive
return compareMatricesAndArrays(x, y.toArray());
} // convert DenseArray into Array
if (type.isDenseMatrix(x)) {
return compareMatricesAndArrays(x.toJSON().data, y);
}
if (type.isDenseMatrix(y)) {
return compareMatricesAndArrays(x, y.toJSON().data);
} // convert scalars to array
if (!Array.isArray(x)) {
return compareMatricesAndArrays([x], y);
}
if (!Array.isArray(y)) {
return compareMatricesAndArrays(x, [y]);
}
return compareArrays(x, y);
}
|
Compare mixed matrix/array types, by converting to same-shaped array.
This comparator is non-deterministic regarding input types.
@param {Array | SparseMatrix | DenseMatrix | *} x
@param {Array | SparseMatrix | DenseMatrix | *} y
@returns {number} Returns the comparison result: -1, 0, or 1
|
compareMatricesAndArrays
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function compareArrays(x, y) {
// compare each value
for (var i = 0, ii = Math.min(x.length, y.length); i < ii; i++) {
var v = compareNatural(x[i], y[i]);
if (v !== 0) {
return v;
}
} // compare the size of the arrays
if (x.length > y.length) {
return 1;
}
if (x.length < y.length) {
return -1;
} // both Arrays have equal size and content
return 0;
}
|
Compare two Arrays
- First, compares value by value
- Next, if all corresponding values are equal,
look at the length: longest array will be considered largest
@param {Array} x
@param {Array} y
@returns {number} Returns the comparison result: -1, 0, or 1
|
compareArrays
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function compareObjects(x, y) {
var keysX = Object.keys(x);
var keysY = Object.keys(y); // compare keys
keysX.sort(naturalSort);
keysY.sort(naturalSort);
var c = compareArrays(keysX, keysY);
if (c !== 0) {
return c;
} // compare values
for (var i = 0; i < keysX.length; i++) {
var v = compareNatural(x[keysX[i]], y[keysY[i]]);
if (v !== 0) {
return v;
}
}
return 0;
}
|
Compare two objects
- First, compare sorted property names
- Next, compare the property values
@param {Object} x
@param {Object} y
@returns {number} Returns the comparison result: -1, 0, or 1
|
compareObjects
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function compareComplexNumbers(x, y) {
if (x.re > y.re) {
return 1;
}
if (x.re < y.re) {
return -1;
}
if (x.im > y.im) {
return 1;
}
if (x.im < y.im) {
return -1;
}
return 0;
}
|
Compare two complex numbers, `x` and `y`:
- First, compare the real values of `x` and `y`
- If equal, compare the imaginary values of `x` and `y`
@params {Complex} x
@params {Complex} y
@returns {number} Returns the comparison result: -1, 0, or 1
|
compareComplexNumbers
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _pow(x, y) {
// Alternatively could define a 'realmode' config option or something, but
// 'predictable' will work for now
if (config.predictable && !isInteger(y) && x < 0) {
// Check to see if y can be represented as a fraction
try {
var yFrac = fraction(y);
var yNum = number(yFrac);
if (y === yNum || Math.abs((y - yNum) / y) < 1e-14) {
if (yFrac.d % 2 === 1) {
return (yFrac.n % 2 === 0 ? 1 : -1) * Math.pow(-x, y);
}
}
} catch (ex) {} // fraction() throws an error if y is Infinity, etc.
// Unable to express y as a fraction, so continue on
} // x^Infinity === 0 if -1 < x < 1
// A real number 0 is returned instead of complex(0)
if (x * x < 1 && y === Infinity || x * x > 1 && y === -Infinity) {
return 0;
} // **for predictable mode** x^Infinity === NaN if x < -1
// N.B. this behavour is different from `Math.pow` which gives
// (-2)^Infinity === Infinity
if (config.predictable && (x < -1 && y === Infinity || x > -1 && x < 0 && y === -Infinity)) {
return NaN;
}
if (isInteger(y) || x >= 0 || config.predictable) {
return Math.pow(x, y);
} else {
return new type.Complex(x, 0).pow(y, 0);
}
}
|
Calculates the power of x to y, x^y, for two numbers.
@param {number} x
@param {number} y
@return {number | Complex} res
@private
|
_pow
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _powArray(x, y) {
if (!isInteger(y) || y < 0) {
throw new TypeError('For A^b, b must be a positive integer (value is ' + y + ')');
} // verify that A is a 2 dimensional square matrix
var s = size(x);
if (s.length !== 2) {
throw new Error('For A^b, A must be 2 dimensional (A has ' + s.length + ' dimensions)');
}
if (s[0] !== s[1]) {
throw new Error('For A^b, A must be square (size is ' + s[0] + 'x' + s[1] + ')');
}
var res = identity(s[0]).valueOf();
var px = x;
while (y >= 1) {
if ((y & 1) === 1) {
res = multiply(px, res);
}
y >>= 1;
px = multiply(px, px);
}
return res;
}
|
Calculate the power of a 2d array
@param {Array} x must be a 2 dimensional, square matrix
@param {number} y a positive, integer value
@returns {Array}
@private
|
_powArray
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _powMatrix(x, y) {
return matrix(_powArray(x.valueOf(), y));
}
|
Calculate the power of a 2d matrix
@param {Matrix} x must be a 2 dimensional, square matrix
@param {number} y a positive, integer value
@returns {Matrix}
@private
|
_powMatrix
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function _zeros(size, format) {
var hasBigNumbers = _normalize(size);
var defaultValue = hasBigNumbers ? new type.BigNumber(0) : 0;
_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 zeros
@param {Array} size
@param {string} [format='default']
@return {Array | Matrix}
@private
|
_zeros
|
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 zeros
@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 zeros must be positive integers');
}
});
}
|
Create an Array or Matrix with zeros
@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
|
function parse(expr, options) {
if (arguments.length !== 1 && arguments.length !== 2) {
throw new ArgumentsError('parse', arguments.length, 1, 2);
} // pass extra nodes
var extraNodes = options && options.nodes ? options.nodes : {};
if (typeof expr === 'string') {
// parse a single expression
return parseStart(expr, extraNodes);
} else if (Array.isArray(expr) || expr instanceof type.Matrix) {
// parse an array or matrix with expressions
return deepMap(expr, function (elem) {
if (typeof elem !== 'string') throw new TypeError('String expected');
return parseStart(elem, extraNodes);
});
} else {
// oops
throw new TypeError('String or matrix expected');
}
} // token types enumeration
|
Parse an expression. Returns a node tree, which can be evaluated by
invoking node.eval().
Syntax:
parse(expr)
parse(expr, options)
parse([expr1, expr2, expr3, ...])
parse([expr1, expr2, expr3, ...], options)
Example:
const node = parse('sqrt(3^2 + 4^2)')
node.compile(math).eval() // 5
let scope = {a:3, b:4}
const node = parse('a * b') // 12
const code = node.compile(math)
code.eval(scope) // 12
scope.a = 5
code.eval(scope) // 20
const nodes = math.parse(['a = 3', 'b = 4', 'a * b'])
nodes[2].compile(math).eval() // 12
@param {string | string[] | Matrix} expr
@param {{nodes: Object<string, Node>}} [options] Available options:
- `nodes` a set of custom nodes
@return {Node | Node[]} node
@throws {Error}
|
parse
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function initialState() {
return {
extraNodes: {},
// current extra nodes, must be careful not to mutate
expression: '',
// current expression
comment: '',
// last parsed comment
index: 0,
// current index in expr
token: '',
// current token
tokenType: TOKENTYPE.NULL,
// type of the token
nestingLevel: 0,
// level of nesting inside parameters, used to ignore newline characters
conditionalLevel: null // when a conditional is being parsed, the level of the conditional is stored here
};
}
|
Parse an expression. Returns a node tree, which can be evaluated by
invoking node.eval().
Syntax:
parse(expr)
parse(expr, options)
parse([expr1, expr2, expr3, ...])
parse([expr1, expr2, expr3, ...], options)
Example:
const node = parse('sqrt(3^2 + 4^2)')
node.compile(math).eval() // 5
let scope = {a:3, b:4}
const node = parse('a * b') // 12
const code = node.compile(math)
code.eval(scope) // 12
scope.a = 5
code.eval(scope) // 20
const nodes = math.parse(['a = 3', 'b = 4', 'a * b'])
nodes[2].compile(math).eval() // 12
@param {string | string[] | Matrix} expr
@param {{nodes: Object<string, Node>}} [options] Available options:
- `nodes` a set of custom nodes
@return {Node | Node[]} node
@throws {Error}
|
initialState
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function currentString(state, length) {
return state.expression.substr(state.index, length);
}
|
View upto `length` characters of the expression starting at the current character.
@param {State} state
@param {number} [length=1] Number of characters to view
@returns {string}
@private
|
currentString
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function currentCharacter(state) {
return currentString(state, 1);
}
|
View the current character. Returns '' if end of expression is reached.
@param {State} state
@returns {string}
@private
|
currentCharacter
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function prevCharacter(state) {
return state.expression.charAt(state.index - 1);
}
|
Preview the previous character from the expression.
@return {string} cNext
@private
|
prevCharacter
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function nextCharacter(state) {
return state.expression.charAt(state.index + 1);
}
|
Preview the next character from the expression.
@return {string} cNext
@private
|
nextCharacter
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function getToken(state) {
state.tokenType = TOKENTYPE.NULL;
state.token = '';
state.comment = ''; // skip over whitespaces
// space, tab, and newline when inside parameters
while (parse.isWhitespace(currentCharacter(state), state.nestingLevel)) {
next(state);
} // skip comment
if (currentCharacter(state) === '#') {
while (currentCharacter(state) !== '\n' && currentCharacter(state) !== '') {
state.comment += currentCharacter(state);
next(state);
}
} // check for end of expression
if (currentCharacter(state) === '') {
// token is still empty
state.tokenType = TOKENTYPE.DELIMITER;
return;
} // check for new line character
if (currentCharacter(state) === '\n' && !state.nestingLevel) {
state.tokenType = TOKENTYPE.DELIMITER;
state.token = currentCharacter(state);
next(state);
return;
}
var c1 = currentCharacter(state);
var c2 = currentString(state, 2);
var c3 = currentString(state, 3);
if (c3.length === 3 && DELIMITERS[c3]) {
state.tokenType = TOKENTYPE.DELIMITER;
state.token = c3;
next(state);
next(state);
next(state);
return;
} // check for delimiters consisting of 2 characters
if (c2.length === 2 && DELIMITERS[c2]) {
state.tokenType = TOKENTYPE.DELIMITER;
state.token = c2;
next(state);
next(state);
return;
} // check for delimiters consisting of 1 character
if (DELIMITERS[c1]) {
state.tokenType = TOKENTYPE.DELIMITER;
state.token = c1;
next(state);
return;
} // check for a number
if (parse.isDigitDot(c1)) {
state.tokenType = TOKENTYPE.NUMBER; // get number, can have a single dot
if (currentCharacter(state) === '.') {
state.token += currentCharacter(state);
next(state);
if (!parse.isDigit(currentCharacter(state))) {
// this is no number, it is just a dot (can be dot notation)
state.tokenType = TOKENTYPE.DELIMITER;
}
} else {
while (parse.isDigit(currentCharacter(state))) {
state.token += currentCharacter(state);
next(state);
}
if (parse.isDecimalMark(currentCharacter(state), nextCharacter(state))) {
state.token += currentCharacter(state);
next(state);
}
}
while (parse.isDigit(currentCharacter(state))) {
state.token += currentCharacter(state);
next(state);
} // check for exponential notation like "2.3e-4", "1.23e50" or "2e+4"
if (currentCharacter(state) === 'E' || currentCharacter(state) === 'e') {
if (parse.isDigit(nextCharacter(state)) || nextCharacter(state) === '-' || nextCharacter(state) === '+') {
state.token += currentCharacter(state);
next(state);
if (currentCharacter(state) === '+' || currentCharacter(state) === '-') {
state.token += currentCharacter(state);
next(state);
} // Scientific notation MUST be followed by an exponent
if (!parse.isDigit(currentCharacter(state))) {
throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"');
}
while (parse.isDigit(currentCharacter(state))) {
state.token += currentCharacter(state);
next(state);
}
if (parse.isDecimalMark(currentCharacter(state), nextCharacter(state))) {
throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"');
}
} else if (nextCharacter(state) === '.') {
next(state);
throw createSyntaxError(state, 'Digit expected, got "' + currentCharacter(state) + '"');
}
}
return;
} // check for variables, functions, named operators
if (parse.isAlpha(currentCharacter(state), prevCharacter(state), nextCharacter(state))) {
while (parse.isAlpha(currentCharacter(state), prevCharacter(state), nextCharacter(state)) || parse.isDigit(currentCharacter(state))) {
state.token += currentCharacter(state);
next(state);
}
if (NAMED_DELIMITERS.hasOwnProperty(state.token)) {
state.tokenType = TOKENTYPE.DELIMITER;
} else {
state.tokenType = TOKENTYPE.SYMBOL;
}
return;
} // something unknown is found, wrong characters -> a syntax error
state.tokenType = TOKENTYPE.UNKNOWN;
while (currentCharacter(state) !== '') {
state.token += currentCharacter(state);
next(state);
}
throw createSyntaxError(state, 'Syntax error in part "' + state.token + '"');
}
|
Get next token in the current string expr.
The token and token type are available as token and tokenType
@private
|
getToken
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function getTokenSkipNewline(state) {
do {
getToken(state);
} while (state.token === '\n'); // eslint-disable-line no-unmodified-loop-condition
}
|
Get next token and skip newline tokens
|
getTokenSkipNewline
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseStart(expression, extraNodes) {
var state = initialState();
_extends(state, {
expression: expression,
extraNodes: extraNodes
});
getToken(state);
var node = parseBlock(state); // check for garbage at the end of the expression
// an expression ends with a empty character '' and tokenType DELIMITER
if (state.token !== '') {
if (state.tokenType === TOKENTYPE.DELIMITER) {
// user entered a not existing operator like "//"
// TODO: give hints for aliases, for example with "<>" give as hint " did you mean !== ?"
throw createError(state, 'Unexpected operator ' + state.token);
} else {
throw createSyntaxError(state, 'Unexpected part "' + state.token + '"');
}
}
return node;
}
|
Start of the parse levels below, in order of precedence
@return {Node} node
@private
|
parseStart
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseBlock(state) {
var node;
var blocks = [];
var visible;
if (state.token !== '' && state.token !== '\n' && state.token !== ';') {
node = parseAssignment(state);
node.comment = state.comment;
} // TODO: simplify this loop
while (state.token === '\n' || state.token === ';') {
// eslint-disable-line no-unmodified-loop-condition
if (blocks.length === 0 && node) {
visible = state.token !== ';';
blocks.push({
node: node,
visible: visible
});
}
getToken(state);
if (state.token !== '\n' && state.token !== ';' && state.token !== '') {
node = parseAssignment(state);
node.comment = state.comment;
visible = state.token !== ';';
blocks.push({
node: node,
visible: visible
});
}
}
if (blocks.length > 0) {
return new BlockNode(blocks);
} else {
if (!node) {
node = new ConstantNode(undefined);
node.comment = state.comment;
}
return node;
}
}
|
Parse a block with expressions. Expressions can be separated by a newline
character '\n', or by a semicolon ';'. In case of a semicolon, no output
of the preceding line is returned.
@return {Node} node
@private
|
parseBlock
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseAssignment(state) {
var name, args, value, valid;
var node = parseConditional(state);
if (state.token === '=') {
if (type.isSymbolNode(node)) {
// parse a variable assignment like 'a = 2/3'
name = node.name;
getTokenSkipNewline(state);
value = parseAssignment(state);
return new AssignmentNode(new SymbolNode(name), value);
} else if (type.isAccessorNode(node)) {
// parse a matrix subset assignment like 'A[1,2] = 4'
getTokenSkipNewline(state);
value = parseAssignment(state);
return new AssignmentNode(node.object, node.index, value);
} else if (type.isFunctionNode(node) && type.isSymbolNode(node.fn)) {
// parse function assignment like 'f(x) = x^2'
valid = true;
args = [];
name = node.name;
node.args.forEach(function (arg, index) {
if (type.isSymbolNode(arg)) {
args[index] = arg.name;
} else {
valid = false;
}
});
if (valid) {
getTokenSkipNewline(state);
value = parseAssignment(state);
return new FunctionAssignmentNode(name, args, value);
}
}
throw createSyntaxError(state, 'Invalid left hand side of assignment operator =');
}
return node;
}
|
Assignment of a function or variable,
- can be a variable like 'a=2.3'
- or a updating an existing variable like 'matrix(2,3:5)=[6,7,8]'
- defining a function like 'f(x) = x^2'
@return {Node} node
@private
|
parseAssignment
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseConditional(state) {
var node = parseLogicalOr(state);
while (state.token === '?') {
// eslint-disable-line no-unmodified-loop-condition
// set a conditional level, the range operator will be ignored as long
// as conditionalLevel === state.nestingLevel.
var prev = state.conditionalLevel;
state.conditionalLevel = state.nestingLevel;
getTokenSkipNewline(state);
var condition = node;
var trueExpr = parseAssignment(state);
if (state.token !== ':') throw createSyntaxError(state, 'False part of conditional expression expected');
state.conditionalLevel = null;
getTokenSkipNewline(state);
var falseExpr = parseAssignment(state); // Note: check for conditional operator again, right associativity
node = new ConditionalNode(condition, trueExpr, falseExpr); // restore the previous conditional level
state.conditionalLevel = prev;
}
return node;
}
|
conditional operation
condition ? truePart : falsePart
Note: conditional operator is right-associative
@return {Node} node
@private
|
parseConditional
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseLogicalOr(state) {
var node = parseLogicalXor(state);
while (state.token === 'or') {
// eslint-disable-line no-unmodified-loop-condition
getTokenSkipNewline(state);
node = new OperatorNode('or', 'or', [node, parseLogicalXor(state)]);
}
return node;
}
|
logical or, 'x or y'
@return {Node} node
@private
|
parseLogicalOr
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseLogicalXor(state) {
var node = parseLogicalAnd(state);
while (state.token === 'xor') {
// eslint-disable-line no-unmodified-loop-condition
getTokenSkipNewline(state);
node = new OperatorNode('xor', 'xor', [node, parseLogicalAnd(state)]);
}
return node;
}
|
logical exclusive or, 'x xor y'
@return {Node} node
@private
|
parseLogicalXor
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseLogicalAnd(state) {
var node = parseBitwiseOr(state);
while (state.token === 'and') {
// eslint-disable-line no-unmodified-loop-condition
getTokenSkipNewline(state);
node = new OperatorNode('and', 'and', [node, parseBitwiseOr(state)]);
}
return node;
}
|
logical and, 'x and y'
@return {Node} node
@private
|
parseLogicalAnd
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseBitwiseOr(state) {
var node = parseBitwiseXor(state);
while (state.token === '|') {
// eslint-disable-line no-unmodified-loop-condition
getTokenSkipNewline(state);
node = new OperatorNode('|', 'bitOr', [node, parseBitwiseXor(state)]);
}
return node;
}
|
bitwise or, 'x | y'
@return {Node} node
@private
|
parseBitwiseOr
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseBitwiseXor(state) {
var node = parseBitwiseAnd(state);
while (state.token === '^|') {
// eslint-disable-line no-unmodified-loop-condition
getTokenSkipNewline(state);
node = new OperatorNode('^|', 'bitXor', [node, parseBitwiseAnd(state)]);
}
return node;
}
|
bitwise exclusive or (xor), 'x ^| y'
@return {Node} node
@private
|
parseBitwiseXor
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseBitwiseAnd(state) {
var node = parseRelational(state);
while (state.token === '&') {
// eslint-disable-line no-unmodified-loop-condition
getTokenSkipNewline(state);
node = new OperatorNode('&', 'bitAnd', [node, parseRelational(state)]);
}
return node;
}
|
bitwise and, 'x & y'
@return {Node} node
@private
|
parseBitwiseAnd
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseRelational(state) {
var params = [parseShift(state)];
var conditionals = [];
var operators = {
'==': 'equal',
'!=': 'unequal',
'<': 'smaller',
'>': 'larger',
'<=': 'smallerEq',
'>=': 'largerEq'
};
while (operators.hasOwnProperty(state.token)) {
// eslint-disable-line no-unmodified-loop-condition
var cond = {
name: state.token,
fn: operators[state.token]
};
conditionals.push(cond);
getTokenSkipNewline(state);
params.push(parseShift(state));
}
if (params.length === 1) {
return params[0];
} else if (params.length === 2) {
return new OperatorNode(conditionals[0].name, conditionals[0].fn, params);
} else {
return new RelationalNode(conditionals.map(function (c) {
return c.fn;
}), params);
}
}
|
Parse a chained conditional, like 'a > b >= c'
@return {Node} node
|
parseRelational
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseShift(state) {
var node, operators, name, fn, params;
node = parseConversion(state);
operators = {
'<<': 'leftShift',
'>>': 'rightArithShift',
'>>>': 'rightLogShift'
};
while (operators.hasOwnProperty(state.token)) {
name = state.token;
fn = operators[name];
getTokenSkipNewline(state);
params = [node, parseConversion(state)];
node = new OperatorNode(name, fn, params);
}
return node;
}
|
Bitwise left shift, bitwise right arithmetic shift, bitwise right logical shift
@return {Node} node
@private
|
parseShift
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseConversion(state) {
var node, operators, name, fn, params;
node = parseRange(state);
operators = {
'to': 'to',
'in': 'to' // alias of 'to'
};
while (operators.hasOwnProperty(state.token)) {
name = state.token;
fn = operators[name];
getTokenSkipNewline(state);
if (name === 'in' && state.token === '') {
// end of expression -> this is the unit 'in' ('inch')
node = new OperatorNode('*', 'multiply', [node, new SymbolNode('in')], true);
} else {
// operator 'a to b' or 'a in b'
params = [node, parseRange(state)];
node = new OperatorNode(name, fn, params);
}
}
return node;
}
|
conversion operators 'to' and 'in'
@return {Node} node
@private
|
parseConversion
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseRange(state) {
var node;
var params = [];
if (state.token === ':') {
// implicit start=1 (one-based)
node = new ConstantNode(1);
} else {
// explicit start
node = parseAddSubtract(state);
}
if (state.token === ':' && state.conditionalLevel !== state.nestingLevel) {
// we ignore the range operator when a conditional operator is being processed on the same level
params.push(node); // parse step and end
while (state.token === ':' && params.length < 3) {
// eslint-disable-line no-unmodified-loop-condition
getTokenSkipNewline(state);
if (state.token === ')' || state.token === ']' || state.token === ',' || state.token === '') {
// implicit end
params.push(new SymbolNode('end'));
} else {
// explicit end
params.push(parseAddSubtract(state));
}
}
if (params.length === 3) {
// params = [start, step, end]
node = new RangeNode(params[0], params[2], params[1]); // start, end, step
} else {
// length === 2
// params = [start, end]
node = new RangeNode(params[0], params[1]); // start, end
}
}
return node;
}
|
parse range, "start:end", "start:step:end", ":", "start:", ":end", etc
@return {Node} node
@private
|
parseRange
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseAddSubtract(state) {
var node, operators, name, fn, params;
node = parseMultiplyDivide(state);
operators = {
'+': 'add',
'-': 'subtract'
};
while (operators.hasOwnProperty(state.token)) {
name = state.token;
fn = operators[name];
getTokenSkipNewline(state);
params = [node, parseMultiplyDivide(state)];
node = new OperatorNode(name, fn, params);
}
return node;
}
|
add or subtract
@return {Node} node
@private
|
parseAddSubtract
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
function parseMultiplyDivide(state) {
var node, last, operators, name, fn;
node = parseImplicitMultiplication(state);
last = node;
operators = {
'*': 'multiply',
'.*': 'dotMultiply',
'/': 'divide',
'./': 'dotDivide',
'%': 'mod',
'mod': 'mod'
};
while (true) {
if (operators.hasOwnProperty(state.token)) {
// explicit operators
name = state.token;
fn = operators[name];
getTokenSkipNewline(state);
last = parseImplicitMultiplication(state);
node = new OperatorNode(name, fn, [node, last]);
} else {
break;
}
}
return node;
}
|
multiply, divide, modulus
@return {Node} node
@private
|
parseMultiplyDivide
|
javascript
|
grimalschi/calque
|
math.js
|
https://github.com/grimalschi/calque/blob/master/math.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.