AvgAccumulator.js 1.5 KB

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