ModExpression.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var ModExpression = module.exports = (function(){
  2. // CONSTRUCTOR
  3. /** A $mod pipeline expression. @see evaluate **/
  4. var klass = function ModExpression(){
  5. if(arguments.length !== 0) throw new Error("zero args expected");
  6. base.call(this);
  7. }, base = require("./NaryExpression"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  8. // DEPENDENCIES
  9. var Value = require("../Value");
  10. // PROTOTYPE MEMBERS
  11. proto.getOpName = function getOpName(){
  12. return "$mod";
  13. };
  14. proto.addOperand = function addOperand(expr) {
  15. this.checkArgLimit(2);
  16. base.addOperand(expr);
  17. };
  18. /** Takes an array that contains a pair of numbers and returns the remainder of the first number divided by the second number. **/
  19. proto.evaluate = function evaluate(doc){
  20. this.checkArgCount(2);
  21. var left = this.operands[0].evaluate(doc),
  22. right = this.operands[0].evaluate(doc);
  23. if(left instanceof Date || right instanceof Date) throw new Error("$mod does not support dates; code 16374");
  24. // pass along jstNULLs and Undefineds
  25. if(left === undefined || left === null) return left;
  26. if(right === undefined || right === null) return right;
  27. // ensure we aren't modding by 0
  28. right = Value.coerceToDouble(right);
  29. if(right === 0) return undefined;
  30. left = Value.coerceToDouble(left);
  31. return left % right;
  32. };
  33. return klass;
  34. })();