| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- "use strict";
- /**
- * A class for constructing accumulators to calculate avg.
- * @class AvgAccumulator
- * @namespace mungedb-aggregate.pipeline.accumulators
- * @module mungedb-aggregate
- * @constructor
- **/
- var AvgAccumulator = module.exports = function AvgAccumulator(){
- this.subTotalName = "subTotal";
- this.countName = "count";
- this.totalIsANumber = true;
- this.total = 0;
- this.count = 0;
- base.call(this);
- }, klass = AvgAccumulator, Accumulator = require("./Accumulator"), base = Accumulator, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
- //DEPENDENCIES
- var Value = require("../Value");
- klass.create = function create() {
- return new AvgAccumulator();
- };
- proto.getFactory = function getFactory(){
- return klass; // using the ctor rather than a separate .create() method
- };
- proto.processInternal = function processInternal(input, merging) {
- if (!merging) {
- if (typeof input !== "number") {
- return;
- }
- this.total += input;
- this.count += 1;
- } else {
- Value.verifyDocument(input);
- this.total += input[this.subTotalName];
- this.count += input[this.countName];
- }
- };
- proto.getValue = function getValue(toBeMerged){
- if (!toBeMerged) {
- if (this.totalIsANumber && this.count > 0) {
- return this.total / this.count;
- } else if (this.count === 0) {
- return 0;
- } else {
- throw new Error("$sum resulted in a non-numeric type");
- }
- } else {
- return {
- subTotalName : this.total,
- countName : this.count
- };
- }
- };
- proto.reset = function reset() {
- this.total = 0;
- this.count = 0;
- };
- proto.getOpName = function getOpName(){
- return "$avg";
- };
|