ModExpression.js 1.5 KB

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