SumAccumulator.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use strict";
  2. /**
  3. * Accumulator for summing values
  4. * @class SumAccumulator
  5. * @namespace mungedb-aggregate.pipeline.accumulators
  6. * @module mungedb-aggregate
  7. * @constructor
  8. **/
  9. var SumAccumulator = module.exports = function SumAccumulator() {
  10. if (arguments.length !== 0) throw new Error("zero args expected");
  11. this.reset();
  12. base.call(this);
  13. }, klass = SumAccumulator, base = require("./Accumulator"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  14. proto.processInternal = function processInternal(input, merging) {
  15. // do nothing with non numeric types
  16. if (typeof input !== "number"){
  17. if (input !== undefined && input !== null) { //NOTE: DEVIATION FROM MONGO: minor fix for 0-like values
  18. this.isNumber = false;
  19. }
  20. return;
  21. }
  22. this.total += input;
  23. };
  24. klass.create = function create() {
  25. return new SumAccumulator();
  26. };
  27. proto.getValue = function getValue(toBeMerged) {
  28. if (this.isNumber) {
  29. return this.total;
  30. } else {
  31. throw new Error("$sum resulted in a non-numeric type; massert code 16000");
  32. }
  33. };
  34. proto.reset = function reset() {
  35. this.isNumber = true;
  36. this.total = 0;
  37. };
  38. proto.getOpName = function getOpName(){
  39. return "$sum";
  40. };