MinMaxAccumulator.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. * @class MinMaxAccumulator
  8. * @namespace munge.pipeline.accumulators
  9. * @module munge
  10. * @constructor
  11. **/
  12. var klass = module.exports = function MinMaxAccumulator(sense){
  13. if(arguments.length > 1 ) throw new Error("expects a single value");
  14. base.call(this);
  15. this.sense = sense; /* 1 for min, -1 for max; used to "scale" comparison */
  16. if ((this.sense !== 1) && (this.sense !== -1)) throw new Error("this should never happen");
  17. }, base = require("./SingleValueAccumulator"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  18. // DEPENDENCIES
  19. var Value = require("../Value");
  20. // PROTOTYPE MEMBERS
  21. proto.getOpName = function getOpName(){
  22. if (this.sense == 1)
  23. return "$min";
  24. return "$max";
  25. };
  26. klass.createMin = function createMin(){
  27. return new MinMaxAccumulator(1);
  28. };
  29. klass.createMax = function createMax(){
  30. return new MinMaxAccumulator(-1);
  31. };
  32. /**
  33. * Takes a document and returns the first value in the document
  34. *
  35. * @param {Object} doc the document source
  36. * @return the first value
  37. **/
  38. proto.evaluate = function evaluate(doc){
  39. if (this.operands.length != 1) throw new Error("this should never happen");
  40. var prhs = this.operands[0].evaluate(doc);
  41. /* if this is the first value, just use it */
  42. if (!base.prototype.getValue.call(this))
  43. this.value = prhs;
  44. else {
  45. /* compare with the current value; swap if appropriate */
  46. var cmp = Value.compare(this.value, prhs) * this.sense;
  47. if (cmp > 0)
  48. this.value = prhs;
  49. }
  50. return this.value;
  51. };
  52. return klass;
  53. })();