WeekExpression.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  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.addOperand(expr);
  18. };
  19. /** Takes a date and returns the week of the year as a number between 0 and 53. **/
  20. proto.evaluate = function evaluate(doc) {
  21. this.checkArgCount(1);
  22. var date = this.operands[0].evaluate(doc),
  23. dayOfWeek = date.getDay(),
  24. dayOfYear = DayOfYearExpression.getDateDayOfYear(date),
  25. prevSundayDayOfYear = dayOfYear - dayOfWeek, // may be negative
  26. nextSundayDayOfYear = prevSundayDayOfYear + 7; // must be positive
  27. // 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.
  28. return (nextSundayDayOfYear / 7) | 0; // also, the `| 0` here truncates this so that we return an integer
  29. };
  30. return klass;
  31. })();