SumAccumulator.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. "use strict";
  2. /**
  3. * Accumulator for summing a field across documents
  4. * @class SumAccumulator
  5. * @namespace mungedb-aggregate.pipeline.accumulators
  6. * @module mungedb-aggregate
  7. * @constructor
  8. **/
  9. var SumAccumulator = module.exports = function SumAccumulator(){
  10. this.total = 0;
  11. this.count = 0;
  12. this.totalIsANumber = true;
  13. base.call(this);
  14. }, klass = SumAccumulator, Accumulator = require("./Accumulator"), base = Accumulator, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  15. // NOTE: Skipping the create function, using the constructor instead
  16. // MEMBER FUNCTIONS
  17. proto.processInternal = function processInternal(input, merging) {
  18. if(typeof input === "number"){ // do nothing with non-numeric types
  19. this.totalIsANumber = true;
  20. this.total += input;
  21. }
  22. this.count++;
  23. return 0;
  24. };
  25. proto.getValue = function getValue(toBeMerged){
  26. if (this.totalIsANumber) {
  27. return this.total;
  28. }
  29. throw new Error("$sum resulted in a non-numeric type");
  30. };
  31. proto.getOpName = function getOpName(){
  32. return "$sum";
  33. };