ModExpression.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. this.fixedArity(2);
  12. if (arguments.length !== 0) throw new Error("zero args expected");
  13. base.call(this);
  14. }, klass = ModExpression,
  15. base = require("./NaryExpression"),
  16. proto = klass.prototype = Object.create(base.prototype, {
  17. constructor: {
  18. value: klass
  19. }
  20. });
  21. // DEPENDENCIES
  22. var Value = require("../Value"),
  23. Expression = require("./Expression");
  24. // PROTOTYPE MEMBERS
  25. proto.getOpName = function getOpName() {
  26. return "$mod";
  27. };
  28. /**
  29. * Takes an array that contains a pair of numbers and returns the remainder of the first number divided by the second number.
  30. * @method evaluate
  31. **/
  32. proto.evaluateInternal = function evaluateInternal(doc) {
  33. this.checkArgCount(2);
  34. var left = this.operands[0].evaluateInternal(doc),
  35. right = this.operands[1].evaluateInternal(doc);
  36. if (left instanceof Date || right instanceof Date) throw new Error("$mod does not support dates; code 16374");
  37. // pass along jstNULLs and Undefineds
  38. if (left === undefined || left === null) return left;
  39. if (right === undefined || right === null) return right;
  40. // ensure we aren't modding by 0
  41. right = Value.coerceToDouble(right);
  42. if (right === 0) return undefined;
  43. left = Value.coerceToDouble(left);
  44. return left % right;
  45. };
  46. /** Register Expression */
  47. Expression.registerExpression("$mod", ModExpression.parse);