SetDifferenceExpression.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. "use strict";
  2. /**
  3. * A $setdifference pipeline expression.
  4. * @see evaluateInternal
  5. * @class SetDifferenceExpression
  6. * @namespace mungedb-aggregate.pipeline.expressions
  7. * @module mungedb-aggregate
  8. * @constructor
  9. **/
  10. var SetDifferenceExpression = module.exports = function SetDifferenceExpression() {
  11. this.nargs = 2;
  12. base.call(this);
  13. }, klass = SetDifferenceExpression,
  14. base = require("./NaryExpression"),
  15. proto = klass.prototype = Object.create(base.prototype, {
  16. constructor: {
  17. value: klass
  18. }
  19. });
  20. // DEPENDENCIES
  21. var Value = require("../Value"),
  22. Expression = require("./Expression"),
  23. Helpers = require("./Helpers")
  24. // PROTOTYPE MEMBERS
  25. proto.getOpName = function getOpName() {
  26. return "$setdifference";
  27. };
  28. /**
  29. * Takes 2 arrays. Returns the difference
  30. * @method evaluateInternal
  31. **/
  32. proto.evaluateInternal = function evaluateInternal(vars) {
  33. var lhs = this.operands[0].evaluateInternal(vars),
  34. rhs = this.operands[1].evaluateInternal(vars);
  35. if (lhs instanceof Array) throw new Error(this.getOpName() + ": object 1 must be an array. Got a(n): " + typeof lhs);
  36. if (rhs instanceof Array) throw new Error(this.getOpName() + ": object 2 must be an array. Got a(n): " + typeof rhs);
  37. var rhsSet = Helpers.arrayToSet(rhs),
  38. returnVec = [];
  39. lhs.forEach(function(key) {
  40. if (-1 === rhsSet.indexOf(key)) {
  41. returnVec.push(key);
  42. }
  43. }, this);
  44. return Value.consume(returnVec);
  45. };
  46. /** Register Expression */
  47. Expression.registerExpression("$setdifference", base.parse(SetDifferenceExpression));