AddExpression.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. "use strict";
  2. /**
  3. * Create an expression that finds the sum of n operands.
  4. * @class AddExpression
  5. * @namespace mungedb-aggregate.pipeline.expressions
  6. * @module mungedb-aggregate
  7. * @constructor
  8. **/
  9. var AddExpression = module.exports = function AddExpression(){
  10. // if (arguments.length !== 0) throw new Error("zero args expected");
  11. base.call(this);
  12. }, klass = AddExpression, base = require("./VariadicExpressionT")(klass), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  13. // DEPENDENCIES
  14. var Value = require("../Value"),
  15. Expression = require("./Expression");
  16. // PROTOTYPE MEMBERS
  17. klass.opName = "$add";
  18. proto.getOpName = function getOpName(){
  19. return klass.opName
  20. };
  21. /**
  22. * Takes an array of one or more numbers and adds them together, returning the sum.
  23. * @method @evaluate
  24. **/
  25. proto.evaluateInternal = function evaluateInternal(vars) {
  26. var total = 0;
  27. for (var i = 0, n = this.operands.length; i < n; ++i) {
  28. var value = this.operands[i].evaluateInternal(vars);
  29. if (value instanceof Date) throw new Error("$add does not support dates; code 16415");
  30. if (typeof value == "string") throw new Error("$add does not support strings; code 16416");
  31. total += Value.coerceToDouble(value);
  32. }
  33. if (typeof total != "number") throw new Error("$add resulted in a non-numeric type; code 16417");
  34. return total;
  35. };
  36. /** Register Expression */
  37. Expression.registerExpression(klass.opName,base.parse(klass));