Q:

Scala collection of dates and group by week

import java.time.LocalDate

case class Day(date: LocalDate, other: String)

val list = Seq(
  Day(LocalDate.of(2016, 2, 1), "text"),
  Day(LocalDate.of(2016, 2, 2), "text"),  // Tuesday
  Day(LocalDate.of(2016, 2, 3), "text"),
  Day(LocalDate.of(2016, 2, 4), "text"),
  Day(LocalDate.of(2016, 2, 5), "text"),
  Day(LocalDate.of(2016, 2, 6), "text"),
  Day(LocalDate.of(2016, 2, 7), "text"),
  Day(LocalDate.of(2016, 2, 8), "text"),
  Day(LocalDate.of(2016, 2, 9), "text"),
  Day(LocalDate.of(2016, 2, 10), "text"),
  Day(LocalDate.of(2016, 2, 11), "text"),
  Day(LocalDate.of(2016, 2, 12), "text"),
  Day(LocalDate.of(2016, 2, 13), "text"),
  Day(LocalDate.of(2016, 2, 14), "text"),
  Day(LocalDate.of(2016, 2, 15), "text"),
  Day(LocalDate.of(2016, 2, 16), "text"),
  Day(LocalDate.of(2016, 2, 17), "text")
)

// hard code, for example Tuesday
def groupDaysBy(list: Seq[Day]): List[List[Day]] = {
  ???
}

val result =
Seq(
  Seq(Day(LocalDate.of(2016, 2, 1), "text")),  // Separate
  Seq(Day(LocalDate.of(2016, 2, 2), "text"),  // Tuesday
    Day(LocalDate.of(2016, 2, 3), "text"),
    Day(LocalDate.of(2016, 2, 4), "text"),
    Day(LocalDate.of(2016, 2, 5), "text"),
    Day(LocalDate.of(2016, 2, 6), "text"),
    Day(LocalDate.of(2016, 2, 7), "text"),
    Day(LocalDate.of(2016, 2, 8), "text")),
  Seq(Day(LocalDate.of(2016, 2, 9), "text"),  // Tuesday
    Day(LocalDate.of(2016, 2, 10), "text"),
    Day(LocalDate.of(2016, 2, 11), "text"),
    Day(LocalDate.of(2016, 2, 12), "text"),
    Day(LocalDate.of(2016, 2, 13), "text"),
    Day(LocalDate.of(2016, 2, 14), "text"),
    Day(LocalDate.of(2016, 2, 15), "text")),
  Seq(Day(LocalDate.of(2016, 2, 16), "text"), // Tuesday
    Day(LocalDate.of(2016, 2, 17), "text"))
)

assert(groupDaysBy(list) == result)

I have a list of Day object, and I want to group every 7 days together and the start date can be any day (from Monday to Sunday, I give Tuesday as an example).
Above is the function and expected result for my requirement. I am wondering how can I take advantage of Scala collection API to achieve without tail recursive?

A:

Here's what you can do:
// hard code, for example Tuesday
def groupDaysBy(list: Seq[Day]): Seq[Seq[Day]] = {
  val (list1,list2)= list.span(_.date.getDayOfWeek != DayOfWeek.TUESDAY)
  Seq(list1) ++ list2.grouped(7)
}

I would recommend taking day as a parameter instead of hardcoding though, so it becomes
// hard code, for example Tuesday
def groupDaysBy(list: Seq[Day], dayOfWeek: DayOfWeek): Seq[Seq[Day]] = {
  val (list1,list2)= list.span(_.date.getDayOfWeek != dayOfWeek)
  Seq(list1) ++ list2.grouped(7)
}

...

assert(groupDaysBy(list, DayOfWeek.TUESDAY) == result)

