MinMaxAccumulator.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 = Object, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  15. // DEPENDENCIES
  16. var Value = require("../Value");
  17. // PROTOTYPE MEMBERS
  18. proto.getOpName = function getOpName(){
  19. if (this.sense == 1) return "$min";
  20. return "$max";
  21. };
  22. klass.createMin = function createMin(){
  23. return new MinMaxAccumulator(1);
  24. };
  25. klass.createMax = function createMax(){
  26. return new MinMaxAccumulator(-1);
  27. };
  28. proto.reset = function reset() {
  29. this.value = undefined;
  30. };
  31. proto.getValue = function getValue(toBeMerged) {
  32. return this.value;
  33. };
  34. proto.processInternal = function processInternal(input, merging) {
  35. // if this is the first value, just use it
  36. if (!this.hasOwnProperty('value')) {
  37. this.value = input;
  38. } else {
  39. // compare with the current value; swap if appropriate
  40. var cmp = Value.compare(this.value, input) * this.sense;
  41. if (cmp > 0) this.value = input;
  42. }
  43. return this.value;
  44. };