AddExpression.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var AddExpression = module.exports = (function(){
  2. // CONSTRUCTOR
  3. /**
  4. * Create an expression that finds the sum of n operands.
  5. *
  6. * @class AddExpression
  7. * @namespace munge.pipeline.expressions
  8. * @module munge
  9. * @constructor
  10. **/
  11. var klass = module.exports = function AddExpression(){
  12. if(arguments.length !== 0) throw new Error("zero args expected");
  13. base.call(this);
  14. }, NaryExpression = require("./NaryExpression"), base = NaryExpression, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  15. // DEPENDENCIES
  16. var Value = require("../Value");
  17. // PROTOTYPE MEMBERS
  18. proto.getOpName = function getOpName(){
  19. return "$add";
  20. };
  21. proto.getFactory = function getFactory(){
  22. return klass; // using the ctor rather than a separate .create() method
  23. };
  24. /** Takes an array of one or more numbers and adds them together, returning the sum. **/
  25. proto.evaluate = function evaluate(doc) {
  26. var total = 0;
  27. for (var i = 0, n = this.operands.length; i < n; ++i) {
  28. var value = this.operands[i].evaluate(doc);
  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. return klass;
  37. })();