MinMaxAccumulator.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. /**
  3. * Constructor for MinMaxAccumulator, wraps SingleValueAccumulator's constructor and adds flag to track whether we have started or not
  4. * @class MinMaxAccumulator
  5. * @namespace mungedb-aggregate.pipeline.accumulators
  6. * @module mungedb-aggregate
  7. * @constructor
  8. **/
  9. var MinMaxAccumulator = module.exports = function MinMaxAccumulator(sense){
  10. if (arguments.length > 1) throw new Error("expects a single value");
  11. base.call(this);
  12. this.sense = sense; /* 1 for min, -1 for max; used to "scale" comparison */
  13. if (this.sense !== 1 && this.sense !== -1) throw new Error("this should never happen");
  14. }, klass = MinMaxAccumulator, base = require("./Accumulator"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  15. // NOTE: Skipping the create function, using the constructor instead
  16. // DEPENDENCIES
  17. var Value = require("../Value");
  18. // MEMBER FUNCTIONS
  19. proto.getOpName = function getOpName(){
  20. if (this.sense == 1) return "$min";
  21. return "$max";
  22. };
  23. klass.createMin = function createMin(){
  24. return new MinMaxAccumulator(1);
  25. };
  26. klass.createMax = function createMax(){
  27. return new MinMaxAccumulator(-1);
  28. };
  29. proto.reset = function reset() {
  30. this.value = undefined;
  31. };
  32. proto.getValue = function getValue(toBeMerged) {
  33. return this.value;
  34. };
  35. proto.processInternal = function processInternal(input, merging) {
  36. // if this is the first value, just use it
  37. if (!this.hasOwnProperty('value')) {
  38. this.value = input;
  39. } else {
  40. // compare with the current value; swap if appropriate
  41. var cmp = Value.compare(this.value, input) * this.sense;
  42. if (cmp > 0) this.value = input;
  43. }
  44. return this.value;
  45. };