WeekExpression.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. base.call(this);
  12. }, klass = WeekExpression, base = require("./FixedArityExpressionT")(klass, 1), proto = klass.prototype = Object.create(base.prototype, {constructor: {value: klass}});
  13. // DEPENDENCIES
  14. var Value = require("../Value"),
  15. DayOfYearExpression = require("./DayOfYearExpression"),
  16. Expression = require("./Expression");
  17. // STATIC METHODS
  18. klass.extract = function extract(date) {
  19. //note: copied from evaluateInternal
  20. var dayOfWeek = date.getUTCDay(),
  21. dayOfYear = DayOfYearExpression.getDateDayOfYear(date),
  22. prevSundayDayOfYear = dayOfYear - dayOfWeek, // may be negative
  23. nextSundayDayOfYear = prevSundayDayOfYear + 7; // must be positive
  24. // 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.
  25. return (nextSundayDayOfYear / 7) | 0; // also, the `| 0` here truncates this so that we return an integer
  26. };
  27. klass.opName = "$week";
  28. // PROTOTYPE MEMBERS
  29. proto.getOpName = function getOpName() {
  30. return klass.opName;
  31. };
  32. /**
  33. * Takes a date and returns the week of the year as a number between 0 and 53.
  34. * Weeks begin on Sundays, and week 1 begins with the first Sunday of the year.
  35. * Days preceding the first Sunday of the year are in week 0.
  36. * This behavior is the same as the “%U” operator to the strftime standard library function.
  37. * @method evaluateInternal
  38. **/
  39. proto.evaluateInternal = function evaluateInternal(vars) {
  40. var date = this.operands[0].evaluateInternal(vars);
  41. return klass.extract(date);
  42. };
  43. /** Register Expression */
  44. Expression.registerExpression(klass.opName, base.parse);