Created
July 17, 2017 10:21
-
-
Save mavarazy/47994e8fd95559e29bbc44616ae15a50 to your computer and use it in GitHub Desktop.
TopTracker combine by description and round in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io._ | |
import java.time.{LocalDate, LocalTime, Month} | |
import scala.io.Source | |
case class Event( | |
description: String, | |
project: String, | |
duration: LocalTime, | |
start: LocalTime, | |
end: LocalTime, | |
date: LocalDate | |
) | |
def toLocalTime(str: String): LocalTime = { | |
val strArr = str.split(":") | |
if (strArr(1).endsWith("pm")) { | |
LocalTime.of((strArr(0).toInt + 12) % 24, strArr(1).substring(0, 2).toInt) | |
} else if (strArr(1).endsWith("am")) { | |
LocalTime.of(strArr(0).toInt, strArr(1).substring(0, 2).toInt) | |
} else { | |
LocalTime.of(strArr(0).toInt, strArr(1).toInt) | |
} | |
} | |
def readDate(month: String, day: String) = { | |
val m = Month.valueOf(month.toUpperCase) | |
LocalDate.of(2017, m, day.substring(0, day.length - 2).toInt) | |
} | |
def readLine(str: String): Option[Event] = { | |
val parts = str.split(",") | |
val date = parts(4).split(" ") | |
if (parts(3) == "—") { | |
None | |
} else { | |
Some( | |
Event( | |
description = parts(0), | |
project = parts(1), | |
duration = toLocalTime(parts(3)), | |
start = toLocalTime(date(0)), | |
end = toLocalTime(date(4)), | |
date = readDate(date(1), date(2)) | |
) | |
) | |
} | |
} | |
def read(f: File) = { | |
Source. | |
fromFile(f). | |
getLines(). | |
filterNot(_.isEmpty). | |
drop(1). | |
map(readLine). | |
flatten | |
} | |
def collectForTheDate(events: List[Event]): Event = { | |
val total = (((events.map(_.duration).map(event => event.getMinute + event.getHour * 60).sum) / 15) + 1 ) * 15 | |
val totalDuration = LocalTime.of(total/60, total % 60) | |
val event = events.head | |
event.copy(duration = totalDuration, end = event.start.plusHours(totalDuration.getHour).plusMinutes(totalDuration.getMinute)) | |
} | |
def readAndCombine(f: File): Iterable[Event] = { | |
read(f). | |
toList. | |
groupBy(_.date). | |
mapValues(_.groupBy(_.description).mapValues(collectForTheDate).values). | |
values. | |
flatten | |
} | |
def readAndCombineToFile(f: File, d: File) = { | |
val writer = new BufferedWriter(new FileWriter(d)) | |
readAndCombine(f).foreach(event => { | |
val dur = event.duration | |
writer.write(s"${event.date},${event.description},${dur.getHour}:${dur.getMinute}:00\n") | |
}) | |
writer.close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment