WeekExpression.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. 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. Expression = require("./Expression");
  18. // PROTOTYPE MEMBERS
  19. proto.getOpName = function getOpName(){
  20. return "$week";
  21. };
  22. /**
  23. * Takes a date and returns the week of the year as a number between 0 and 53.
  24. * Weeks begin on Sundays, and week 1 begins with the first Sunday of the year.
  25. * Days preceding the first Sunday of the year are in week 0.
  26. * This behavior is the same as the “%U” operator to the strftime standard library function.
  27. * @method evaluateInternal
  28. **/
  29. proto.evaluateInternal = function evaluateInternal(doc) {
  30. this.checkArgCount(1);
  31. var date = this.operands[0].evaluateInternal(doc),
  32. dayOfWeek = date.getUTCDay(),
  33. dayOfYear = DayOfYearExpression.getDateDayOfYear(date),
  34. prevSundayDayOfYear = dayOfYear - dayOfWeek, // may be negative
  35. nextSundayDayOfYear = prevSundayDayOfYear + 7; // must be positive
  36. // 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.
  37. return (nextSundayDayOfYear / 7) | 0; // also, the `| 0` here truncates this so that we return an integer
  38. };
  39. /** Register Expression */
  40. Expression.registerExpression("$week",WeekExpression.parse);