ModExpression.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. base.call(this);
  12. }, klass = ModExpression,
  13. FixedArityExpression = require("./FixedArityExpressionT")(klass, 2),
  14. base = FixedArityExpression,
  15. proto = klass.prototype = Object.create(base.prototype, {
  16. constructor: {
  17. value: klass
  18. }
  19. });
  20. // DEPENDENCIES
  21. var Value = require("../Value"),
  22. Expression = require("./Expression");
  23. // PROTOTYPE MEMBERS
  24. proto.getOpName = function getOpName() {
  25. return "$mod";
  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.evaluateInternal = function evaluateInternal(vars) {
  32. this.checkArgCount(2);
  33. var left = this.operands[0].evaluateInternal(vars),
  34. right = this.operands[1].evaluateInternal(vars);
  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. /** Register Expression */
  46. Expression.registerExpression("$mod", base.parse);