WeekExpression.js 1.7 KB

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