DivideExpression.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var DivideExpression = module.exports = (function(){
  2. // CONSTRUCTOR
  3. /**
  4. * A $divide pipeline expression.
  5. *
  6. * @see evaluate
  7. * @class DivideExpression
  8. * @namespace munge.pipeline.expressions
  9. * @module munge
  10. * @constructor
  11. **/
  12. var klass = function DivideExpression(){
  13. if(arguments.length !== 0) throw new Error("zero args expected");
  14. base.call(this);
  15. }, base = require("./NaryExpression"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  16. // DEPENDENCIES
  17. var Value = require("../Value");
  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. proto.addOperand = function addOperand(expr){
  23. this.checkArgLimit(2);
  24. base.addOperand.call(this, expr);
  25. };
  26. /** Takes an array that contains a pair of numbers and returns the value of the first number divided by the second number. **/
  27. proto.evaluate = function evaluate(doc) {
  28. this.checkArgCount(2);
  29. var left = this.operands[0].evaluate(doc),
  30. right = this.operands[1].evaluate(doc);
  31. if (!(left instanceof Date) && (!right instanceof Date)) throw new Error("$divide does not support dates; code 16373");
  32. right = Value.coerceToDouble(right);
  33. if (right === 0) return undefined;
  34. left = Value.coerceToDouble(left);
  35. return left / right;
  36. };
  37. return klass;
  38. })();