IndexOfExpression.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use strict";
  2. var IndexOfExpression = module.exports = (function(){
  3. // CONSTRUCTOR
  4. /**
  5. * An $indexOf pipeline expression.
  6. *
  7. * @see evaluate
  8. * @class IndexOfExpression
  9. * @namespace mungedb.aggregate.pipeline.expressions
  10. * @module mungedb-aggregate
  11. * @constructor
  12. **/
  13. var klass = function IndexOfExpression(){
  14. if(arguments.length !== 0) throw new Error("zero args expected");
  15. base.call(this);
  16. }, base = require("./NaryExpression"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  17. // PROTOTYPE MEMBERS
  18. proto.getOpName = function getOpName(){
  19. return "$indexOf";
  20. };
  21. proto.addOperand = function addOperand(expr) {
  22. this.checkArgLimit(2);
  23. base.prototype.addOperand.call(this, expr);
  24. };
  25. /**
  26. * Use the $indexOf operator with the following syntax: { $indexOf: [ <needle>, <haystack> ] }
  27. * @method evaluate
  28. **/
  29. proto.evaluate = function evaluate(doc){
  30. this.checkArgCount(2);
  31. var left = this.operands[0].evaluate(doc);
  32. if (left === undefined) return undefined;
  33. var right = this.operands[1].evaluate(doc);
  34. if (right === undefined) return undefined;
  35. if (!(right instanceof Array)) throw new Error("UserAssertion: expected the 2nd arg of the $indexOf expression to be an Array but got " + (typeof right === "object" ? right.constructor.name : typeof right));
  36. return right.indexOf(left);
  37. };
  38. return klass;
  39. })();