mathjs
Version:
Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser and offers an integrated solution to work with numbers, big numbers, complex numbers, units, and matrices.
99 lines (84 loc) • 2.37 kB
JavaScript
var Node = require('./Node'),
isBoolean = require('../../util/boolean').isBoolean;
/**
* @constructor BlockNode
* @extends {Node}
* Holds a set with nodes
*/
function BlockNode() {
if (!(this instanceof BlockNode)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
this.params = [];
}
BlockNode.prototype = new Node();
/**
* Add an expression. If visible = false, the expression will be evaluated
* but not returned in the output.
* @param {Node} expr
* @param {Boolean} [visible=true]
*/
BlockNode.prototype.add = function (expr, visible) {
if (visible === undefined) visible = true;
// validate input
if (!(expr instanceof Node)) throw new TypeError('Node expected for parameter "expr"');
if (!isBoolean(visible)) throw new TypeError('Boolean expected for parameter "visible"');
var index = this.params.length;
this.params[index] = {
node: expr,
visible: visible
};
};
/**
* Compile the node to javascript code
* @param {Object} defs Object which can be used to define functions
* or constants globally available for the compiled
* expression
* @return {String} js
* @private
*/
BlockNode.prototype._compile = function (defs) {
var params = this.params.map(function (param) {
var js = param.node._compile(defs);
if (param.visible) {
return 'results.push(' + js + ');';
}
else {
return js + ';';
}
});
return '(function () {' +
'var results = [];' +
params.join('') +
'return results;' +
'})()';
};
/**
* Find all nodes matching given filter
* @param {Object} filter See Node.find for a description of the filter options
* @returns {Node[]} nodes
*/
BlockNode.prototype.find = function (filter) {
var nodes = [];
// check itself
if (this.match(filter)) {
nodes.push(this);
}
// search in parameters
var params = this.params;
for (var i = 0, len = params.length; i < len; i++) {
nodes = nodes.concat(params[i].node.find(filter));
}
return nodes;
};
/**
* Get string representation
* @return {String} str
* @override
*/
BlockNode.prototype.toString = function() {
return this.params.map(function (param) {
return param.node.toString() + (param.visible ? '' : ';');
}).join('\n');
};
module.exports = BlockNode;