WeekExpression.js 1.6 KB

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