SetIntersectionExpression.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. /**
  3. * A $setintersection pipeline expression.
  4. * @class SetIntersectionExpression
  5. * @namespace mungedb-aggregate.pipeline.expressions
  6. * @module mungedb-aggregate
  7. * @constructor
  8. */
  9. var SetIntersectionExpression = module.exports = function SetIntersectionExpression() {
  10. if (arguments.length !== 0) throw new Error(klass.name + ": no args expected");
  11. base.call(this);
  12. }, klass = SetIntersectionExpression, base = require("./VariadicExpressionT")(SetIntersectionExpression), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  13. var Value = require("../Value"),
  14. Expression = require("./Expression"),
  15. ValueSet = require("../ValueSet");
  16. proto.evaluateInternal = function evaluateInternal(vars) {
  17. var n = this.operands.length,
  18. currentIntersection = new ValueSet();
  19. for (var i = 0; i < n; i++){
  20. var nextEntry = this.operands[i].evaluateInternal(vars);
  21. if (nextEntry === undefined || nextEntry === null){
  22. return null;
  23. }
  24. if (!(nextEntry instanceof Array))
  25. throw new Error("All operands of " + this.getOpName() + "must be arrays. One " +
  26. "argument is of type: " + Value.getType(nextEntry) + "; uassert code 17047");
  27. if (i === 0){
  28. currentIntersection.insertRange(nextEntry);
  29. } else {
  30. var nextSet = new ValueSet(nextEntry);
  31. if (currentIntersection.size() > nextSet.size()) {
  32. // to iterate over whichever is the smaller set
  33. nextSet.swap(currentIntersection);
  34. }
  35. for (var itKey in currentIntersection.set) {
  36. if (!nextSet.hasKey(itKey)) {
  37. currentIntersection.eraseKey(itKey);
  38. }
  39. }
  40. }
  41. if (currentIntersection.empty()) {
  42. break;
  43. }
  44. }
  45. var result = currentIntersection.values();
  46. return result;
  47. };
  48. Expression.registerExpression("$setIntersection", base.parse);
  49. proto.getOpName = function getOpName() {
  50. return "$setIntersection";
  51. };
  52. proto.isAssociativeAndCommutative = function isAssociativeAndCommutative() {
  53. return true;
  54. };