DivideExpression.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. var DivideExpression = module.exports = (function(){
  2. // CONSTRUCTOR
  3. /** A $divide pipeline expression. @see evaluate **/
  4. var klass = function DivideExpression(){
  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(){ //TODO: try to move this to a static and/or instance field instead of a getter function
  12. return "$divide";
  13. };
  14. proto.addOperand = function addOperand(expr){
  15. this.checkArgLimit(2);
  16. base.addOperand.call(this, expr);
  17. };
  18. /** Takes an array that contains a pair of numbers and returns the value of the first number divided by the second number. **/
  19. proto.evaluate = function evaluate(doc) {
  20. this.checkArgCount(2);
  21. var left = this.operands[0].evaluate(doc),
  22. right = this.operands[1].evaluate(doc);
  23. if (!(left instanceof Date) && (!right instanceof Date)) throw new Error("$divide does not support dates; code 16373");
  24. right = Value.coerceToDouble(right);
  25. if (right === 0) return undefined;
  26. left = Value.coerceToDouble(left);
  27. return left / right;
  28. };
  29. return klass;
  30. })();