AddExpression.js 1.4 KB

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