FirstAccumulator.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. var FirstAccumulator = module.exports = (function(){
  2. // CONSTRUCTOR
  3. /**
  4. * Constructor for FirstAccumulator, wraps SingleValueAccumulator's constructor and
  5. * adds flag to track whether we have started or not
  6. *
  7. **/
  8. var klass = module.exports = function FirstAccumulator(){
  9. base.call(this);
  10. this.started = 0; //TODO: hack to get around falsy values making us keep going
  11. }, base = require("./SingleValueAccumulator"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  12. // PROTOTYPE MEMBERS
  13. proto.getOpName = function getOpName(){
  14. return "$first";
  15. };
  16. proto.getFactory = function getFactory(){
  17. return klass; // using the ctor rather than a separate .create() method
  18. };
  19. /**
  20. * Takes a document and returns the first value in the document
  21. *
  22. * @param {Object} doc the document source
  23. * @return the first value
  24. **/
  25. proto.evaluate = function evaluate(doc){
  26. if (this.operands.length != 1) throw new Error("this should never happen");
  27. /* only remember the first value seen */
  28. if (!base.prototype.getValue.call(this) && this.started === 0) {
  29. this.value = this.operands[0].evaluate(doc);
  30. this.started = 1;
  31. }
  32. return this.value;
  33. };
  34. return klass;
  35. })();