DivideExpression.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. var DivideExpression = module.exports = (function(){
  3. // CONSTRUCTOR
  4. /**
  5. * A $divide pipeline expression.
  6. *
  7. * @see evaluate
  8. * @class DivideExpression
  9. * @namespace mungedb.aggregate.pipeline.expressions
  10. * @module mungedb-aggregate
  11. * @constructor
  12. **/
  13. var klass = function DivideExpression(){
  14. if(arguments.length !== 0) throw new Error("zero args expected");
  15. base.call(this);
  16. }, base = require("./NaryExpression"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  17. // DEPENDENCIES
  18. var Value = require("../Value");
  19. // PROTOTYPE MEMBERS
  20. proto.getOpName = function getOpName(){ //TODO: try to move this to a static and/or instance field instead of a getter function
  21. return "$divide";
  22. };
  23. proto.addOperand = function addOperand(expr){
  24. this.checkArgLimit(2);
  25. base.prototype.addOperand.call(this, expr);
  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 evaluate
  30. **/
  31. proto.evaluate = function evaluate(doc) {
  32. this.checkArgCount(2);
  33. var left = this.operands[0].evaluate(doc),
  34. right = this.operands[1].evaluate(doc);
  35. if (!(left instanceof Date) && (!right instanceof Date)) throw new Error("$divide does not support dates; code 16373");
  36. right = Value.coerceToDouble(right);
  37. if (right === 0) return undefined;
  38. left = Value.coerceToDouble(left);
  39. return left / right;
  40. };
  41. return klass;
  42. })();