AddExpression.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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, NaryExpression = require("./NaryExpression"), base = NaryExpression, 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. proto.getOpName = function getOpName(){
  18. return "$add";
  19. };
  20. /**
  21. * Takes an array of one or more numbers and adds them together, returning the sum.
  22. * @method @evaluate
  23. **/
  24. proto.evaluateInternal = function evaluateInternal(vars) {
  25. var total = 0;
  26. for (var i = 0, n = this.operands.length; i < n; ++i) {
  27. var value = this.operands[i].evaluateInternal(vars);
  28. if (value instanceof Date) throw new Error("$add does not support dates; code 16415");
  29. if (typeof value == "string") throw new Error("$add does not support strings; code 16416");
  30. total += Value.coerceToDouble(value);
  31. }
  32. if (typeof total != "number") throw new Error("$add resulted in a non-numeric type; code 16417");
  33. return total;
  34. };
  35. /** Register Expression */
  36. Expression.registerExpression("$add",base.parse(AddExpression));