OrExpression.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. /**
  3. * An $or pipeline expression.
  4. * @see evaluate
  5. * @class OrExpression
  6. * @namespace mungedb-aggregate.pipeline.expressions
  7. * @module mungedb-aggregate
  8. * @constructor
  9. **/
  10. var OrExpression = module.exports = function OrExpression(){
  11. if (arguments.length !== 0) throw new Error("zero args expected");
  12. base.call(this);
  13. }, klass = OrExpression, base = require("./NaryExpression"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  14. // DEPENDENCIES
  15. var Value = require("../Value"),
  16. ConstantExpression = require("./ConstantExpression"),
  17. CoerceToBoolExpression = require("./CoerceToBoolExpression");
  18. // PROTOTYPE MEMBERS
  19. proto.getOpName = function getOpName(){
  20. return "$or";
  21. };
  22. /**
  23. * Takes an array of one or more values and returns true if any of the values in the array are true. Otherwise $or returns false.
  24. * @method evaluate
  25. **/
  26. proto.evaluate = function evaluate(doc){
  27. for(var i = 0, n = this.operands.length; i < n; ++i){
  28. var value = this.operands[i].evaluate(doc);
  29. if (Value.coerceToBool(value)) return true;
  30. }
  31. return false;
  32. };
  33. proto.optimize = function optimize() {
  34. var pE = base.prototype.optimize.call(this); // optimize the disjunction as much as possible
  35. if (!(pE instanceof OrExpression)) return pE; // if the result isn't a disjunction, we can't do anything
  36. var pOr = pE;
  37. // Check the last argument on the result; if it's not const (as promised
  38. // by ExpressionNary::optimize(),) then there's nothing we can do.
  39. var n = pOr.operands.length;
  40. // ExpressionNary::optimize() generates an ExpressionConstant for {$or:[]}.
  41. if (!n) throw new Error("OrExpression must have operands!");
  42. var pLast = pOr.operands[n - 1];
  43. if (!(pLast instanceof ConstantExpression)) return pE;
  44. // Evaluate and coerce the last argument to a boolean. If it's true, then we can replace this entire expression.
  45. var last = Value.coerceToBool(pLast.evaluate());
  46. if (last) return new ConstantExpression(true);
  47. // If we got here, the final operand was false, so we don't need it anymore.
  48. // If there was only one other operand, we don't need the conjunction either. Note we still need to keep the promise that the result will be a boolean.
  49. if (n == 2) return new CoerceToBoolExpression(pOr.operands[0]);
  50. // Remove the final "false" value, and return the new expression.
  51. pOr.operands.length = n - 1;
  52. return pE;
  53. };
  54. proto.getFactory = function getFactory(){
  55. return klass; // using the ctor rather than a separate .create() method
  56. };