FirstAccumulator.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. "use strict";
  2. /**
  3. * Constructor for FirstAccumulator, wraps SingleValueAccumulator's constructor and adds flag to track whether we have started or not
  4. * @class FirstAccumulator
  5. * @namespace mungedb-aggregate.pipeline.accumulators
  6. * @module mungedb-aggregate
  7. * @constructor
  8. **/
  9. var FirstAccumulator = module.exports = function FirstAccumulator(){
  10. base.call(this);
  11. this.started = 0; //TODO: hack to get around falsy values making us keep going
  12. }, klass = FirstAccumulator, base = require("./SingleValueAccumulator"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  13. // PROTOTYPE MEMBERS
  14. proto.getOpName = function getOpName(){
  15. return "$first";
  16. };
  17. proto.getFactory = function getFactory(){
  18. return klass; // using the ctor rather than a separate .create() method
  19. };
  20. /**
  21. * Takes a document and returns the first value in the document
  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. };