MinMaxAccumulator.js 1.7 KB

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