DivideExpression.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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.fixedArity(2);
  12. if (arguments.length !== 0) throw new Error("zero 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(doc) {
  27. this.checkArgCount(2);
  28. var left = this.operands[0].evaluateInternal(doc),
  29. right = this.operands[1].evaluateInternal(doc);
  30. if (!(left instanceof Date) && (!right instanceof Date)) throw new Error("$divide does not support dates; code 16373");
  31. right = Value.coerceToDouble(right);
  32. if (right === 0) return undefined;
  33. left = Value.coerceToDouble(left);
  34. return left / right;
  35. };
  36. /** Register Expression */
  37. Expression.registerExpression("$divide",DivideExpression.parse);