SumAccumulator.js 964 B

123456789101112131415161718192021222324252627282930313233343536
  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. proto.processInternal = function processInternal(input, merging) {
  16. if(typeof input === "number"){ // do nothing with non-numeric types
  17. this.totalIsANumber = true;
  18. this.total += input;
  19. }
  20. this.count++;
  21. return 0;
  22. };
  23. proto.getValue = function getValue(toBeMerged){
  24. if (this.totalIsANumber) {
  25. return this.total;
  26. }
  27. throw new Error("$sum resulted in a non-numeric type");
  28. };
  29. proto.getOpName = function getOpName(){
  30. return "$sum";
  31. };