AvgAccumulator.js 978 B

123456789101112131415161718192021222324252627282930313233
  1. "use strict";
  2. /**
  3. * A class for constructing accumulators to calculate avg.
  4. * @class AvgAccumulator
  5. * @namespace mungedb-aggregate.pipeline.accumulators
  6. * @module mungedb-aggregate
  7. * @constructor
  8. **/
  9. var AvgAccumulator = module.exports = function AvgAccumulator(){
  10. this.subTotalName = "subTotal";
  11. this.countName = "count";
  12. this.totalIsANumber = true;
  13. base.call(this);
  14. }, klass = AvgAccumulator, SumAccumulator = require("./SumAccumulator"), base = SumAccumulator, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  15. proto.getFactory = function getFactory(){
  16. return klass; // using the ctor rather than a separate .create() method
  17. };
  18. proto.getValue = function getValue(){
  19. if (this.totalIsANumber && this.count > 0) {
  20. return this.total / this.count;
  21. } else if (this.count === 0) {
  22. return 0;
  23. } else {
  24. throw new Error("$sum resulted in a non-numeric type");
  25. }
  26. };
  27. proto.getOpName = function getOpName(){
  28. return "$avg";
  29. };