WeekExpression.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. var WeekExpression = module.exports = (function(){
  2. // CONSTRUCTOR
  3. /**
  4. * A $week pipeline expression.
  5. *
  6. * @see evaluate
  7. * @class WeekExpression
  8. * @namespace mungedb.aggregate.pipeline.expressions
  9. * @module mungedb-aggregate
  10. * @constructor
  11. **/
  12. var klass = function WeekExpression(){
  13. if(arguments.length !== 0) throw new Error("zero args expected");
  14. base.call(this);
  15. }, base = require("./NaryExpression"), proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  16. // DEPENDENCIES
  17. var Value = require("../Value"),
  18. DayOfYearExpression = require("./DayOfYearExpression");
  19. // PROTOTYPE MEMBERS
  20. proto.getOpName = function getOpName(){
  21. return "$week";
  22. };
  23. proto.addOperand = function addOperand(expr) {
  24. this.checkArgLimit(1);
  25. base.prototype.addOperand.call(this, expr);
  26. };
  27. /**
  28. * Takes a date and returns the week of the year as a number between 0 and 53.
  29. * Weeks begin on Sundays, and week 1 begins with the first Sunday of the year.
  30. * Days preceding the first Sunday of the year are in week 0.
  31. * This behavior is the same as the “%U” operator to the strftime standard library function.
  32. * @method evaluate
  33. **/
  34. proto.evaluate = function evaluate(doc) {
  35. this.checkArgCount(1);
  36. var date = this.operands[0].evaluate(doc),
  37. dayOfWeek = date.getDay(),
  38. dayOfYear = DayOfYearExpression.getDateDayOfYear(date),
  39. prevSundayDayOfYear = dayOfYear - dayOfWeek, // may be negative
  40. nextSundayDayOfYear = prevSundayDayOfYear + 7; // must be positive
  41. // Return the zero based index of the week of the next sunday, equal to the one based index of the week of the previous sunday, which is to be returned.
  42. return (nextSundayDayOfYear / 7) | 0; // also, the `| 0` here truncates this so that we return an integer
  43. };
  44. return klass;
  45. })();