CoerceToBoolExpression.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. "use strict";
  2. /**
  3. * internal expression for coercing things to booleans
  4. * @class CoerceToBoolExpression
  5. * @namespace mungedb-aggregate.pipeline.expressions
  6. * @module mungedb-aggregate
  7. * @constructor
  8. */
  9. var CoerceToBoolExpression = module.exports = function CoerceToBoolExpression(theExpression){
  10. if (arguments.length !== 1) throw new Error(klass.name + ": expected args: expr");
  11. this.expression = theExpression;
  12. base.call(this);
  13. }, klass = CoerceToBoolExpression, base = require("./Expression"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}}); //jshint ignore:line
  14. var Value = require("../Value"),
  15. AndExpression = require("./AndExpression"),
  16. OrExpression = require("./OrExpression"),
  17. NotExpression = require("./NotExpression");
  18. klass.create = function create(expression) {
  19. var newExpr = new CoerceToBoolExpression(expression);
  20. return newExpr;
  21. };
  22. proto.optimize = function optimize() {
  23. // optimize the operand
  24. this.expression = this.expression.optimize();
  25. // if the operand already produces a boolean, then we don't need this
  26. // LATER - Expression to support a "typeof" query?
  27. var expr = this.expression;
  28. if (expr instanceof AndExpression ||
  29. expr instanceof OrExpression ||
  30. expr instanceof NotExpression ||
  31. expr instanceof CoerceToBoolExpression)
  32. return expr;
  33. return this;
  34. };
  35. proto.addDependencies = function addDependencies(deps, path) {
  36. this.expression.addDependencies(deps);
  37. };
  38. proto.evaluateInternal = function evaluateInternal(vars) {
  39. var result = this.expression.evaluateInternal(vars);
  40. return Value.coerceToBool(result);
  41. };
  42. proto.serialize = function serialize(explain) {
  43. // When not explaining, serialize to an $and expression. When parsed, the $and expression
  44. // will be optimized back into a ExpressionCoerceToBool.
  45. var name = explain ? "$coerceToBool" : "$and",
  46. obj = {};
  47. obj[name] = [this.expression.serialize(explain)];
  48. return obj;
  49. };