CoerceToBoolExpression.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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}});
  14. var Value = require("../Value"),
  15. AndExpression = require("./AndExpression"),
  16. OrExpression = require("./OrExpression"),
  17. NotExpression = require("./NotExpression"),
  18. Expression = require("./Expression");
  19. klass.create = function create(expression) {
  20. var newExpr = new CoerceToBoolExpression(expression);
  21. return newExpr;
  22. };
  23. proto.optimize = function optimize() {
  24. // optimize the operand
  25. this.expression = this.expression.optimize();
  26. // if the operand already produces a boolean, then we don't need this
  27. // LATER - Expression to support a "typeof" query?
  28. var expr = this.expression;
  29. if (expr instanceof AndExpression ||
  30. expr instanceof OrExpression ||
  31. expr instanceof NotExpression ||
  32. expr instanceof CoerceToBoolExpression)
  33. return expr;
  34. return this;
  35. };
  36. proto.addDependencies = function addDependencies(deps, path) {
  37. this.expression.addDependencies(deps);
  38. };
  39. proto.evaluateInternal = function evaluateInternal(vars) {
  40. var result = this.expression.evaluateInternal(vars);
  41. return Value.coerceToBool(result);
  42. };
  43. proto.serialize = function serialize(explain) {
  44. // When not explaining, serialize to an $and expression. When parsed, the $and expression
  45. // will be optimized back into a ExpressionCoerceToBool.
  46. var name = explain ? "$coerceToBool" : "$and",
  47. obj = {};
  48. obj[name] = [this.expression.serialize(explain)];
  49. return obj;
  50. };