DivideExpression.js 1.5 KB

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