AddExpression.js 1.5 KB

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