mirror of
https://github.com/josdejong/mathjs.git
synced 2025-12-08 19:46:04 +00:00
73 lines
1.5 KiB
JavaScript
73 lines
1.5 KiB
JavaScript
var Node = require('./Node');
|
|
|
|
/**
|
|
* @constructor AssignmentNode
|
|
* Define a symbol, like "a = 3.2"
|
|
*
|
|
* @param {String} name Symbol name
|
|
* @param {Node} expr The expression defining the symbol
|
|
* @param {Scope} scope Scope to store the result
|
|
*/
|
|
function AssignmentNode(name, expr, scope) {
|
|
this.name = name;
|
|
this.expr = expr;
|
|
this.scope = scope;
|
|
}
|
|
|
|
AssignmentNode.prototype = new Node();
|
|
|
|
/**
|
|
* Evaluate the assignment
|
|
* @return {*} result
|
|
*/
|
|
AssignmentNode.prototype.eval = function() {
|
|
if (this.expr === undefined) {
|
|
throw new Error('Undefined symbol ' + this.name);
|
|
}
|
|
|
|
var result = this.expr.eval();
|
|
this.scope.set(this.name, result);
|
|
|
|
return result;
|
|
};
|
|
|
|
/**
|
|
* Compile the node to javascript code
|
|
* @param {Object} math math.js instance
|
|
* @return {String} js
|
|
* @private
|
|
*/
|
|
AssignmentNode.prototype._compile = function (math) {
|
|
return 'scope["' + this.name + '"] = ' + this.expr._compile(math) + '';
|
|
};
|
|
|
|
/**
|
|
* Find all nodes matching given filter
|
|
* @param {Object} filter See Node.find for a description of the filter settings
|
|
* @returns {Node[]} nodes
|
|
*/
|
|
AssignmentNode.prototype.find = function (filter) {
|
|
var nodes = [];
|
|
|
|
// check itself
|
|
if (this.match(filter)) {
|
|
nodes.push(this);
|
|
}
|
|
|
|
// search in expression
|
|
if (this.expr) {
|
|
nodes = nodes.concat(this.expr.find(filter));
|
|
}
|
|
|
|
return nodes;
|
|
};
|
|
|
|
/**
|
|
* Get string representation
|
|
* @return {String}
|
|
*/
|
|
AssignmentNode.prototype.toString = function() {
|
|
return this.name + ' = ' + this.expr.toString();
|
|
};
|
|
|
|
module.exports = AssignmentNode; |