WeekExpression.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. /**
  3. * A $week pipeline expression.
  4. * @see evaluateInternal
  5. * @class WeekExpression
  6. * @namespace mungedb-aggregate.pipeline.expressions
  7. * @module mungedb-aggregate
  8. * @constructor
  9. **/
  10. var WeekExpression = module.exports = function WeekExpression() {
  11. this.nargs = 1;
  12. base.call(this);
  13. }, klass = WeekExpression,
  14. base = require("./NaryExpression"),
  15. proto = klass.prototype = Object.create(base.prototype, {
  16. constructor: {
  17. value: klass
  18. }
  19. });
  20. // DEPENDENCIES
  21. var Value = require("../Value"),
  22. DayOfYearExpression = require("./DayOfYearExpression"),
  23. Expression = require("./Expression");
  24. // PROTOTYPE MEMBERS
  25. proto.getOpName = function getOpName() {
  26. return "$week";
  27. };
  28. /**
  29. * Takes a date and returns the week of the year as a number between 0 and 53.
  30. * Weeks begin on Sundays, and week 1 begins with the first Sunday of the year.
  31. * Days preceding the first Sunday of the year are in week 0.
  32. * This behavior is the same as the “%U” operator to the strftime standard library function.
  33. * @method evaluateInternal
  34. **/
  35. proto.evaluateInternal = function evaluateInternal(vars) {
  36. var date = this.operands[0].evaluateInternal(vars),
  37. dayOfWeek = date.getUTCDay(),
  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. /** Register Expression */
  45. Expression.registerExpression("$week", base.parse(WeekExpression));