weekday.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // =============================================================================
  2. // Weekday
  3. // =============================================================================
  4. export type WeekdayStr = 'MO' | 'TU' | 'WE' | 'TH' | 'FR' | 'SA' | 'SU'
  5. export const ALL_WEEKDAYS: WeekdayStr[] = [
  6. 'MO',
  7. 'TU',
  8. 'WE',
  9. 'TH',
  10. 'FR',
  11. 'SA',
  12. 'SU',
  13. ]
  14. export class Weekday {
  15. public readonly weekday: number
  16. public readonly n?: number
  17. constructor(weekday: number, n?: number) {
  18. if (n === 0) throw new Error("Can't create weekday with n == 0")
  19. this.weekday = weekday
  20. this.n = n
  21. }
  22. static fromStr(str: WeekdayStr): Weekday {
  23. return new Weekday(ALL_WEEKDAYS.indexOf(str))
  24. }
  25. // __call__ - Cannot call the object directly, do it through
  26. // e.g. RRule.TH.nth(-1) instead,
  27. nth(n: number) {
  28. return this.n === n ? this : new Weekday(this.weekday, n)
  29. }
  30. // __eq__
  31. equals(other: Weekday) {
  32. return this.weekday === other.weekday && this.n === other.n
  33. }
  34. // __repr__
  35. toString() {
  36. let s: string = ALL_WEEKDAYS[this.weekday]
  37. if (this.n) s = (this.n > 0 ? '+' : '') + String(this.n) + s
  38. return s
  39. }
  40. getJsWeekday() {
  41. return this.weekday === 6 ? 0 : this.weekday + 1
  42. }
  43. }