SumAccumulator.js 949 B

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