MultiplyExpression.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. var MultiplyExpression = module.exports = (function(){
  2. // CONSTRUCTOR
  3. /** A $multiply pipeline expression. @see evaluate **/
  4. var klass = function MultiplyExpression(){
  5. if(arguments.length !== 0) throw new Error("zero args expected");
  6. base.call(this);
  7. }, base = require("./NaryExpression"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  8. // DEPENDENCIES
  9. var Value = require("../Value");
  10. // PROTOTYPE MEMBERS
  11. proto.getOpName = function getOpName(){
  12. return "$multiply";
  13. };
  14. proto.addOperand = function addOperand(expr) {
  15. this.checkArgLimit(1);
  16. base.addOperand(expr);
  17. };
  18. /** Takes an array of one or more numbers and multiples them, returning the resulting product. **/
  19. proto.evaluate = function evaluate(doc){
  20. var product = 1;
  21. for(var i = 0, n = this.operands.length; i < n; ++i){
  22. var value = this.operands[i].evaluate(doc);
  23. if(value instanceof Date) throw new Error("$multiply does not support dates; code 16375");
  24. product *= Value.coerceToDouble(value);
  25. }
  26. if(typeof(product) != "number") throw new Error("$multiply resulted in a non-numeric type; code 16418");
  27. return product;
  28. };
  29. proto.getFactory = function getFactory(){
  30. return klass; // using the ctor rather than a separate .create() method
  31. };
  32. return klass;
  33. })();