AllElementsTrueExpression.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. /**
  3. * Create an expression that returns true exists in all elements.
  4. * @class AllElementsTrueExpression
  5. * @namespace mungedb-aggregate.pipeline.expressions
  6. * @module mungedb-aggregate
  7. * @constructor
  8. **/
  9. var AllElementsTrueExpression = module.exports = function AllElementsTrueExpression() {
  10. base.call(this);
  11. },
  12. klass = AllElementsTrueExpression,
  13. FixedArityExpression = require("./FixedArityExpressionT")(klass, 1),
  14. base = FixedArityExpression,
  15. proto = klass.prototype = Object.create(base.prototype, {
  16. constructor: {
  17. value: klass
  18. }
  19. });
  20. // DEPENDENCIES
  21. var Value = require("../Value"),
  22. CoerceToBoolExpression = require("./CoerceToBoolExpression"),
  23. Expression = require("./Expression");
  24. // PROTOTYPE MEMBERS
  25. proto.getOpName = function getOpName() {
  26. return "$allElementsTrue";
  27. };
  28. /**
  29. * Takes an array of one or more numbers and returns true if all.
  30. * @method @evaluateInternal
  31. **/
  32. proto.evaluateInternal = function evaluateInternal(vars) {
  33. var arr = this.operands[0].evaluateInternal(vars);
  34. if (!(arr instanceof Array)) throw new Error("uassert 17040: argument of " + this.getOpName() + " must be an array, but is " + typeof arr);
  35. //Deviation from mongo. This is needed so that empty array is handled properly.
  36. if (arr.length === 0){
  37. return false;
  38. }
  39. for (var i = 0, n = arr.length; i < n; ++i) {
  40. if (! Value.coerceToBool(arr[i])){
  41. return false;
  42. }
  43. }
  44. return true;
  45. };
  46. /** Register Expression */
  47. Expression.registerExpression("$allElementsTrue", base.parse);