SubtractExpression.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. /**
  3. * A $subtract pipeline expression.
  4. * @see evaluateInternal
  5. * @class SubtractExpression
  6. * @extends mungedb-aggregate.pipeline.expressions.FixedArityExpressionT
  7. * @namespace mungedb-aggregate.pipeline.expressions
  8. * @module mungedb-aggregate
  9. * @constructor
  10. */
  11. var SubtractExpression = module.exports = function SubtractExpression() {
  12. base.call(this);
  13. }, klass = SubtractExpression, base = require("./FixedArityExpressionT")(SubtractExpression, 2), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  14. var Value = require("../Value"),
  15. Expression = require("./Expression");
  16. proto.evaluateInternal = function evaluateInternal(vars) {
  17. var lhs = this.operands[0].evaluateInternal(vars),
  18. rhs = this.operands[1].evaluateInternal(vars);
  19. if (typeof lhs === "number" && typeof rhs === "number") {
  20. return lhs - rhs;
  21. } else if (lhs === null || lhs === undefined || rhs === null || rhs === undefined) {
  22. return null;
  23. } else if (lhs instanceof Date) {
  24. if (rhs instanceof Date) {
  25. var timeDelta = lhs - rhs;
  26. return timeDelta;
  27. } else if (typeof rhs === "number") {
  28. var millisSinceEpoch = lhs - Value.coerceToLong(rhs);
  29. return millisSinceEpoch;
  30. } else {
  31. throw new Error("can't $subtract a " +
  32. Value.getType(rhs) +
  33. " from a Date" +
  34. "; uassert code 16613");
  35. }
  36. } else {
  37. throw new Error("can't $subtract a " +
  38. Value.getType(rhs) +
  39. " from a " +
  40. Value.getType(lhs) +
  41. "; uassert code 16556");
  42. }
  43. };
  44. Expression.registerExpression("$subtract", base.parse);
  45. proto.getOpName = function getOpName() {
  46. return "$subtract";
  47. };