src/main/scala/meetup.scala

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.Calendar
import java.util.GregorianCalendar

object Meetup {
  def apply(month: Integer, year: Integer) = new Meetup(month, year)

  val Mon = Calendar.MONDAY
  val Tue = Calendar.TUESDAY
  val Wed = Calendar.WEDNESDAY
  val Thu = Calendar.THURSDAY
  val Fri = Calendar.FRIDAY
  val Sat = Calendar.SATURDAY
  val Sun = Calendar.SUNDAY
}

class Meetup(month: Integer, year: Integer) {
  private val firstOfMonth = new GregorianCalendar(year, month - 1, 1)
  private val daysInMonth = firstOfMonth.getActualMaximum(Calendar.DAY_OF_MONTH)
  private val monthStartWeekday = firstOfMonth.get(Calendar.DAY_OF_WEEK)

  private def nth(selector: Seq[Int] => Int)(weekday: Int) = {
    val weekdayOffset = ((weekday - monthStartWeekday) + 7) % 7
    val matchingWeekdays = (1 + weekdayOffset) to daysInMonth by 7
    new GregorianCalendar(year, month - 1, selector(matchingWeekdays))
  }

  def first = nth(_(0)) _
  def second = nth(_(1)) _
  def third = nth(_(2)) _
  def fourth = nth(_(3)) _
  def last = nth(_.last) _
  def teenth = nth(_.find(13 to 19 contains _).get) _
}

@abo64 thinks this looks great

Comments

Learned a bit about partial function application and tidied up as much as possible to reduce duplication.

Wonder if there's something better I can do with all those weekday val's?

helenst commented 18 April 2016 at 10:41 UTC

guess you cannot do much better as long as you stick w/ GregorianCalendar. :-)

abo64 commented 18 April 2016 at 10:47 UTC

You're not logged in right now. Please login via GitHub to comment