ModExpression.js 1.5 KB

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