ModExpression.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. "use strict";
  2. var ModExpression = module.exports = (function(){
  3. // CONSTRUCTOR
  4. /**
  5. * An $Mod pipeline expression.
  6. *
  7. * @see evaluate
  8. * @class ModExpression
  9. * @namespace mungedb.aggregate.pipeline.expressions
  10. * @module mungedb-aggregate
  11. * @constructor
  12. **/
  13. var klass = function ModExpression(){
  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(){
  21. return "$mod";
  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 remainder 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("$mod does not support dates; code 16374");
  36. // pass along jstNULLs and Undefineds
  37. if(left === undefined || left === null) return left;
  38. if(right === undefined || right === null) return right;
  39. // ensure we aren't modding by 0
  40. right = Value.coerceToDouble(right);
  41. if(right === 0) return undefined;
  42. left = Value.coerceToDouble(left);
  43. return left % right;
  44. };
  45. return klass;
  46. })();