AddExpression.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. /**
  3. * Create an expression that finds the sum of n operands.
  4. * @class AddExpression
  5. * @extends mungedb-aggregate.pipeline.expressions.VariadicExpressionT
  6. * @namespace mungedb-aggregate.pipeline.expressions
  7. * @module mungedb-aggregate
  8. * @constructor
  9. */
  10. var AddExpression = module.exports = function AddExpression(){
  11. if (arguments.length !== 0) throw new Error(klass.name + ": no args expected");
  12. base.call(this);
  13. }, klass = AddExpression, base = require("./VariadicExpressionT")(AddExpression), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  14. var Value = require("../Value"),
  15. Expression = require("./Expression");
  16. proto.evaluateInternal = function evaluateInternal(vars) {
  17. var total = 0, //NOTE: DEVIATION FROM MONGO: no need to track narrowest so just use one var
  18. haveDate = false;
  19. var n = this.operands.length;
  20. for (var i = 0; i < n; ++i) {
  21. var val = this.operands[i].evaluateInternal(vars);
  22. if (typeof val === "number") {
  23. total += val;
  24. } else if (val instanceof Date) {
  25. if (haveDate)
  26. throw new Error("only one Date allowed in an $add expression; uassert code 16612");
  27. haveDate = true;
  28. total += val.getTime();
  29. } else if (val === undefined || val === null) {
  30. return null;
  31. } else {
  32. throw new Error("$add only supports numeric or date types, not " +
  33. Value.getType(val) + "; uasserted code 16554");
  34. }
  35. }
  36. if (haveDate) {
  37. return new Date(total);
  38. } else if (typeof total === "number") {
  39. return total;
  40. } else {
  41. throw new Error("$add resulted in a non-numeric type; massert code 16417");
  42. }
  43. };
  44. Expression.registerExpression("$add", base.parse);
  45. proto.getOpName = function getOpName(){
  46. return "$add";
  47. };
  48. proto.isAssociativeAndCommutative = function isAssociativeAndCommutative() {
  49. return true;
  50. };