MinMaxAccumulator.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. /**
  3. * Accumulator to get the min or max value
  4. * @class MinMaxAccumulator
  5. * @namespace mungedb-aggregate.pipeline.accumulators
  6. * @module mungedb-aggregate
  7. * @constructor
  8. **/
  9. var MinMaxAccumulator = module.exports = function MinMaxAccumulator(theSense){
  10. if (arguments.length != 1) throw new Error("expects a single value");
  11. this._sense = theSense; // 1 for min, -1 for max; used to "scale" comparison
  12. base.call(this);
  13. if (this._sense !== 1 && this._sense !== -1) throw new Error("Assertion failure");
  14. }, klass = MinMaxAccumulator, base = require("./Accumulator"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  15. var Value = require("../Value");
  16. proto.processInternal = function processInternal(input, merging) {
  17. // nullish values should have no impact on result
  18. if (!(input === undefined || input === null)) {
  19. // compare with the current value; swap if appropriate
  20. var cmp = Value.compare(this._val, input) * this._sense;
  21. if (cmp > 0 || this._val === undefined) { // missing is lower than all other values
  22. this._val = input;
  23. }
  24. }
  25. };
  26. proto.getValue = function getValue(toBeMerged) {
  27. return this._val;
  28. };
  29. proto.reset = function reset() {
  30. this._val = undefined;
  31. };
  32. klass.createMin = function createMin(){
  33. return new MinMaxAccumulator(1);
  34. };
  35. klass.createMax = function createMax(){
  36. return new MinMaxAccumulator(-1);
  37. };
  38. proto.getOpName = function getOpName() {
  39. if (this._sense == 1) return "$min";
  40. return "$max";
  41. };