ModExpression.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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.prototype.addOperand.call(this, expr);
  17. };
  18. /**
  19. * Takes an array that contains a pair of numbers and returns the remainder of the first number divided by the second number.
  20. **/
  21. proto.evaluate = function evaluate(doc){
  22. this.checkArgCount(2);
  23. var left = this.operands[0].evaluate(doc),
  24. right = this.operands[1].evaluate(doc);
  25. if(left instanceof Date || right instanceof Date) throw new Error("$mod does not support dates; code 16374");
  26. // pass along jstNULLs and Undefineds
  27. if(left === undefined || left === null) return left;
  28. if(right === undefined || right === null) return right;
  29. // ensure we aren't modding by 0
  30. right = Value.coerceToDouble(right);
  31. if(right === 0) return undefined;
  32. left = Value.coerceToDouble(left);
  33. return left % right;
  34. };
  35. return klass;
  36. })();