DivideExpression.js 1.4 KB

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