AvgAccumulator.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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.reset();
  11. base.call(this);
  12. }, klass = AvgAccumulator, Accumulator = require("./Accumulator"), base = Accumulator, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  13. var Value = require("../Value");
  14. var SUB_TOTAL_NAME = "subTotal";
  15. var COUNT_NAME = "count";
  16. proto.processInternal = function processInternal(input, merging) {
  17. if (!merging) {
  18. // non numeric types have no impact on average
  19. if (typeof input != "number") return;
  20. this._total += input;
  21. this._count += 1;
  22. } else {
  23. // We expect an object that contains both a subtotal and a count.
  24. // This is what getValue(true) produced below.
  25. if (!(input instanceof Object)) throw new Error("Assertion error");
  26. this._total += input[SUB_TOTAL_NAME];
  27. this._count += input[COUNT_NAME];
  28. }
  29. };
  30. klass.create = function create() {
  31. return new AvgAccumulator();
  32. };
  33. proto.getValue = function getValue(toBeMerged) {
  34. if (!toBeMerged) {
  35. if (this._count === 0)
  36. return 0.0;
  37. return this._total / this._count;
  38. } else {
  39. var doc = {};
  40. doc[SUB_TOTAL_NAME] = this._total;
  41. doc[COUNT_NAME] = this._count;
  42. return doc;
  43. }
  44. };
  45. proto.reset = function reset() {
  46. this._total = 0;
  47. this._count = 0;
  48. };
  49. proto.getOpName = function getOpName() {
  50. return "$avg";
  51. };