DivideExpression.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. base.call(this);
  12. }, klass = DivideExpression,
  13. FixedArityExpression = require("./FixedArityExpressionT")(klass, 2),
  14. base = FixedArityExpression,
  15. proto = klass.prototype = Object.create(base.prototype, {
  16. constructor:{
  17. value:klass
  18. }
  19. });
  20. // DEPENDENCIES
  21. var Value = require("../Value"),
  22. Expression = require("./Expression");
  23. // PROTOTYPE MEMBERS
  24. proto.getOpName = function getOpName(){ //TODO: try to move this to a static and/or instance field instead of a getter function
  25. return "$divide";
  26. };
  27. /**
  28. * Takes an array that contains a pair of numbers and returns the value of the first number divided by the second number.
  29. * @method evaluateInternal
  30. **/
  31. proto.evaluateInternal = function evaluateInternal(vars) {
  32. var left = this.operands[0].evaluateInternal(vars),
  33. right = this.operands[1].evaluateInternal(vars);
  34. if (!(left instanceof Date) && (!right instanceof Date)) throw new Error("$divide does not support dates; code 16373");
  35. right = Value.coerceToDouble(right);
  36. if (right === 0) return undefined;
  37. left = Value.coerceToDouble(left);
  38. return left / right;
  39. };
  40. /** Register Expression */
  41. Expression.registerExpression("$divide",base.parse);