MinMaxAccumulator.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. var MinMaxAccumulator = module.exports = (function(){
  2. // CONSTRUCTOR
  3. /**
  4. * Constructor for MinMaxAccumulator, wraps SingleValueAccumulator's constructor and
  5. * adds flag to track whether we have started or not
  6. *
  7. **/
  8. var klass = module.exports = function MinMaxAccumulator(sense){
  9. if(arguments.length > 1 ) throw new Error("expects a single value");
  10. base.call(this);
  11. this.sense = sense; /* 1 for min, -1 for max; used to "scale" comparison */
  12. if ((this.sense !== 1) && (this.sense !== -1)) throw new Error("this should never happen");
  13. }, base = require("./SingleValueAccumulator"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  14. // DEPENDENCIES
  15. var Value = require("../Value");
  16. // PROTOTYPE MEMBERS
  17. proto.getOpName = function getOpName(){
  18. if (this.sense == 1)
  19. 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. *
  31. * @param {Object} doc the document source
  32. * @return the first value
  33. **/
  34. proto.evaluate = function evaluate(doc){
  35. if (this.operands.length != 1) throw new Error("this should never happen");
  36. var prhs = this.operands[0].evaluate(doc);
  37. /* if this is the first value, just use it */
  38. if (!base.prototype.getValue.call(this))
  39. this.value = prhs;
  40. else {
  41. /* compare with the current value; swap if appropriate */
  42. var cmp = Value.compare(this.value, prhs) * this.sense;
  43. if (cmp > 0)
  44. this.value = prhs;
  45. }
  46. return this.value;
  47. };
  48. return klass;
  49. })();