DivideExpression.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. "use strict";
  2. /**
  3. * A $divide pipeline expression.
  4. * @see evaluate
  5. * @class DivideExpression
  6. * @namespace mungedb-aggregate.pipeline.expressions
  7. * @module mungedb-aggregate
  8. * @constructor
  9. **/
  10. var DivideExpression = module.exports = function DivideExpression(){
  11. if (arguments.length !== 0) throw new Error("zero args expected");
  12. base.call(this);
  13. }, klass = DivideExpression, base = require("./NaryExpression"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  14. // DEPENDENCIES
  15. var Value = require("../Value");
  16. // PROTOTYPE MEMBERS
  17. proto.getOpName = function getOpName(){ //TODO: try to move this to a static and/or instance field instead of a getter function
  18. return "$divide";
  19. };
  20. proto.addOperand = function addOperand(expr){
  21. this.checkArgLimit(2);
  22. base.prototype.addOperand.call(this, expr);
  23. };
  24. /**
  25. * Takes an array that contains a pair of numbers and returns the value of the first number divided by the second number.
  26. * @method evaluate
  27. **/
  28. proto.evaluate = function evaluate(doc) {
  29. this.checkArgCount(2);
  30. var left = this.operands[0].evaluate(doc),
  31. right = this.operands[1].evaluate(doc);
  32. if (!(left instanceof Date) && (!right instanceof Date)) throw new Error("$divide does not support dates; code 16373");
  33. right = Value.coerceToDouble(right);
  34. if (right === 0) return undefined;
  35. left = Value.coerceToDouble(left);
  36. return left / right;
  37. };