MinMaxAccumulator.js 1.7 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 = require("./SingleValueAccumulator"), 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. /**
  29. * Takes a document and returns the first value in the document
  30. * @param {Object} doc the document source
  31. * @return the first value
  32. **/
  33. proto.evaluate = function evaluate(doc){
  34. if (this.operands.length != 1) throw new Error("this should never happen");
  35. var prhs = this.operands[0].evaluate(doc);
  36. // if this is the first value, just use it
  37. if (!this.hasOwnProperty('value')) {
  38. this.value = prhs;
  39. } else {
  40. // compare with the current value; swap if appropriate
  41. var cmp = Value.compare(this.value, prhs) * this.sense;
  42. if (cmp > 0) this.value = prhs;
  43. }
  44. return this.value;
  45. };