Reputation: 48450
I have some Ruby code I am attempting to refactor using Scala. I'll put an example of the code below, but the dynamic nature of Ruby makes this trivial to write (also helps that I'm better versed in Ruby than Scala). Here's the code in Ruby:
I have a bunch of constants defined like the following
REG_WEEK_1_START = Date.parse('2013-09-05')
REG_WEEK_1_END = Date.parse('2013-09-09')
REG_WEEK_2_START = Date.parse('2013-09-12')
REG_WEEK_2_END = Date.parse('2013-09-16')
REG_WEEK_3_START = Date.parse('2013-09-19')
REG_WEEK_3_END = Date.parse('2013-09-23')
Then, in order to figure out if I'm in a certain week (and you can't use a continuous function here, because weeks can be anywhere from 1 to 7 days later on in the real world example), I use this trivial loop:
def get_week
date = Date.now
for i in 1..17
return i if date >= const_get("REG_WEEK_#{i}_START") && date <= const_get("REG_WEEK_#{i}_END")
end
return 0
end
Doing this in Ruby proved trivial because you can call a constant by name dynamically using the const_get
method. Now, I began this example in Scala, and I'm guessing the right answer will be to somehow Map or use Enums, but I'm not sure how to piece it together, but clearly something like this will not work:
def getCurrentWeek: Int = {
val REG_WEEK_1_START = MyDateTimeHelper.parseDate("20130905")
val REG_WEEK_1_END = MyDateTimeHelper.parseDate("20130909")
val REG_WEEK_2_START = MyDateTimeHelper.parseDate("20130912")
val REG_WEEK_2_END = MyDateTimeHelper.parseDate("20130916")
.... more DATES ...
}
How to loop here is where I'm stuck in Scala. Or if I should even be looping at all here as I'm not familiar with Scala data structures, so there might be a more optimal way of solving this. Anyone with more Scala experience have a solution for how to figure out if the current date falls between each of those START and END values, that would be ideal.
Upvotes: 1
Views: 86
Reputation: 8281
First, it's a good idea to create a case class to represent period of time
case class Period(start: Date, end: Date)
So, declare constants like that :
val period1 = Period(d1, d2)
val period2 = Period(d3, d4)
And create a sequence and iterate over with a for comprehension
for (d <- Seq(period1, period2)) yield {…}
Upvotes: 1