SumAccumulator.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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.evaluate = function evaluate(doc){
  16. if (this.operands.length != 1) throw new Error("this should never happen");
  17. var v = this.operands[0].evaluate(doc);
  18. if (typeof v !== "number") { // do nothing with non-numeric types
  19. return 0;
  20. } else {
  21. this.totalIsANumber = true;
  22. this.total += v;
  23. }
  24. this.count++;
  25. return 0;
  26. };
  27. proto.getValue = function getValue(){
  28. if (this.totalIsANumber) {
  29. return this.total;
  30. }
  31. throw new Error("$sum resulted in a non-numeric type");
  32. };
  33. proto.getOpName = function getOpName(){
  34. return "$sum";
  35. };