FirstAccumulator.js 1.3 KB

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