AddExpression.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. var AddExpression = module.exports = (function(){
  2. // CONSTRUCTOR
  3. /** Create an expression that finds the sum of n operands. **/
  4. var klass = module.exports = function AddExpression(){
  5. if(arguments.length !== 0) throw new Error("zero args expected");
  6. base.call(this);
  7. }, NaryExpression = require("./NaryExpression"), base = NaryExpression, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  8. // DEPENDENCIES
  9. var Value = require("../Value");
  10. // PROTOTYPE MEMBERS
  11. proto.getOpName = function getOpName(){
  12. return "$add";
  13. };
  14. proto.getFactory = function getFactory(){
  15. return klass; // using the ctor rather than a separate .create() method
  16. };
  17. /** Takes an array of one or more numbers and adds them together, returning the sum. **/
  18. proto.evaluate = function evaluate(doc) {
  19. var total = 0;
  20. for (var i = 0, n = this.operands.length; i < n; ++i) {
  21. var value = this.operands[i].evaluate(doc);
  22. if (value instanceof Date) throw new Error("$add does not support dates; code 16415");
  23. if (typeof(value) == "string") throw new Error("$add does not support strings; code 16416");
  24. total += Value.coerceToDouble(value);
  25. }
  26. if (typeof(total) != "number") throw new Error("$add resulted in a non-numeric type; code 16417");
  27. return total;
  28. };
  29. return klass;
  30. })();