SumAccumulator.js 1.1 KB

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