OrExpression.js 2.4 KB

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