SumAccumulator.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. var SumAccumulator = module.exports = (function(){
  3. // Constructor
  4. /**
  5. * Accumulator for summing a field across documents
  6. *
  7. * @class SumAccumulator
  8. * @namespace munge.pipeline.accumulators
  9. * @module munge
  10. * @constructor
  11. **/
  12. var klass = module.exports = function SumAccumulator(){
  13. this.total = 0;
  14. this.count = 0;
  15. this.totalIsANumber = true;
  16. base.call(this);
  17. }, Accumulator = require("./Accumulator"), base = Accumulator, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  18. proto.evaluate = function evaluate(doc){
  19. if(this.operands.length != 1) throw new Error("this should never happen");
  20. var v = this.operands[0].evaluate(doc);
  21. if(typeof v !== "number"){ // do nothing with non-numeric types
  22. return 0;
  23. }
  24. else {
  25. this.totalIsANumber = true;
  26. this.total += v;
  27. }
  28. this.count++;
  29. return 0;
  30. };
  31. proto.getValue = function getValue(){
  32. if(this.totalIsANumber)
  33. return this.total;
  34. else
  35. throw new Error("$sum resulted in a non-numeric type");
  36. };
  37. proto.getOpName = function getOpName(){
  38. return "$sum";
  39. };
  40. return klass;
  41. })();