WeekExpression.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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, base = require("./FixedArityExpressionT")(klass, 1), 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. // STATIC MEMBERS
  19. klass.extract = function extract(date) {
  20. //note: copied from evaluateInternal
  21. dayOfWeek = date.getUTCDay(),
  22. dayOfYear = DayOfYearExpression.getDateDayOfYear(date),
  23. prevSundayDayOfYear = dayOfYear - dayOfWeek, // may be negative
  24. nextSundayDayOfYear = prevSundayDayOfYear + 7; // must be positive
  25. // 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.
  26. return (nextSundayDayOfYear / 7) | 0; // also, the `| 0` here truncates this so that we return an integer
  27. };
  28. klass.opName = "$week";
  29. // PROTOTYPE MEMBERS
  30. proto.getOpName = function getOpName() {
  31. return klass.opName;
  32. };
  33. /**
  34. * Takes a date and returns the week of the year as a number between 0 and 53.
  35. * Weeks begin on Sundays, and week 1 begins with the first Sunday of the year.
  36. * Days preceding the first Sunday of the year are in week 0.
  37. * This behavior is the same as the “%U” operator to the strftime standard library function.
  38. * @method evaluateInternal
  39. **/
  40. proto.evaluateInternal = function evaluateInternal(vars) {
  41. var date = this.operands[0].evaluateInternal(vars);
  42. //NOTE: DEVIATION FROM MONGO: need to return a Value object. Our Value class only consists of static helpers at the moment. We need a value instance to be consistent.
  43. return klass.extract(date);
  44. };
  45. /** Register Expression */
  46. Expression.registerExpression(klass.opName, base.parse(klass));