CondExpression.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. "use strict";
  2. /**
  3. * $cond expression; @see evaluate
  4. * @class CondExpression
  5. * @namespace mungedb-aggregate.pipeline.expressions
  6. * @module mungedb-aggregate
  7. * @constructor
  8. **/
  9. var CondExpression = module.exports = function CondExpression(vars) {
  10. this.nargs = 3;
  11. this.pCond = this.evaluateInternal(vars);
  12. this.idx = this.pCond.coerceToBool() ? 1 : 2;
  13. if (arguments.length !== 3) throw new Error("three args expected");
  14. base.call(this);
  15. }, klass = CondExpression,
  16. base = require("./NaryExpression"),
  17. proto = klass.prototype = Object.create(base.prototype, {
  18. constructor: {
  19. value: klass
  20. }
  21. });
  22. // DEPENDENCIES
  23. var Value = require("../Value"),
  24. Expression = require("./Expression");
  25. // PROTOTYPE MEMBERS
  26. proto.getOpName = function getOpName() {
  27. return "$cond";
  28. };
  29. klass.parse = function parse(expr, vps) {
  30. this.checkArgLimit(3);
  31. // if not an object, return;
  32. if (typeof(expr) !== Object)
  33. return Expression.parse(expr, vps);
  34. // verify
  35. if (Expression.parseOperand(expr) !== "$cond")
  36. throw new Error("Invalid expression");
  37. var ret = new CondExpression();
  38. var ex = Expression.parseObject(expr);
  39. var args = Expression.parseOperand(expr, vps);
  40. if (args[0] !== "if")
  41. throw new Error("Missing 'if' parameter to $cond");
  42. if (args[1] !== "then")
  43. throw new Error("Missing 'then' parameter to $cond");
  44. if (args[2] !== "else")
  45. throw new Error("Missing 'else' parameter to $cond");
  46. return ret;
  47. };
  48. /**
  49. * Use the $cond operator with the following syntax: { $cond: [ <boolean-expression>, <true-case>, <false-case> ] }
  50. * @method evaluate
  51. **/
  52. proto.evaluateInternal = function evaluateInternal(vars) {
  53. var pCond1 = this.operands[0].evaluateInternal(vars);
  54. this.idx = 0;
  55. if (pCond1.coerceToBool()) {
  56. this.idx = 1;
  57. } else {
  58. this.idx = 2;
  59. }
  60. return this.operands[this.idx].evaluateInternal(vars);
  61. };
  62. /** Register Expression */
  63. Expression.registerExpression("$cond", klass.parse);