FirstAccumulator.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. * @class FirstAccumulator
  8. * @namespace munge.pipeline.accumulators
  9. * @module munge
  10. * @constructor
  11. **/
  12. var klass = module.exports = function FirstAccumulator(){
  13. base.call(this);
  14. this.started = 0; //TODO: hack to get around falsy values making us keep going
  15. }, base = require("./SingleValueAccumulator"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  16. // PROTOTYPE MEMBERS
  17. proto.getOpName = function getOpName(){
  18. return "$first";
  19. };
  20. proto.getFactory = function getFactory(){
  21. return klass; // using the ctor rather than a separate .create() method
  22. };
  23. /**
  24. * Takes a document and returns the first value in the document
  25. *
  26. * @param {Object} doc the document source
  27. * @return the first value
  28. **/
  29. proto.evaluate = function evaluate(doc){
  30. if (this.operands.length != 1) throw new Error("this should never happen");
  31. /* only remember the first value seen */
  32. if (!base.prototype.getValue.call(this) && this.started === 0) {
  33. this.value = this.operands[0].evaluate(doc);
  34. this.started = 1;
  35. }
  36. return this.value;
  37. };
  38. return klass;
  39. })();