FirstAccumulator.js 1.3 KB

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