-
-
Save matsutomu/90ab9aa624b1b95592cd42ec2a97ad51 to your computer and use it in GitHub Desktop.
This file contains 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 scala.collection.immutable.TreeMap | |
// import scala.io.Source | |
object Main extends App { | |
// val file = Source.fromFile("", "utf-8") | |
// val lines = file.getLines.dropWhile(l => l.trim.isEmpty) | |
val lines = List( | |
f"- 2018年01月18日 木曜日 19:00", | |
"- これはテストです1", | |
f"- 2018年01月19日 金曜日 19:00", | |
"- これはテストです2", | |
"- これはテストです3", | |
f"- 2018年01月18日 木曜日 19:00", | |
"- これはテストです4" | |
) | |
val result: DiaryConvert = lines.foldLeft(DiaryConvert()) { (d, l) => | |
d.parseLine(l) | |
} | |
println(result) | |
} | |
case class DiaryConvert(currentKey: String = "", | |
acc: TreeMap[String, StringBuilder] = TreeMap.empty[String, StringBuilder]){ | |
val dateTimeSep = """- (\d{4})年(\d{2})月(\d{2})日 .曜日 (\d{2}:\d{2})""".r | |
private def parseKey(line: String): Option[String] = line match { | |
case dateTimeSep(year, month, day, time) => | |
Some(s"$year-$month-$day $time") | |
case _ => None | |
} | |
private def adder(key: String, line: String): DiaryConvert = | |
DiaryConvert(key, acc.+(key -> | |
acc.getOrElse(key, new StringBuilder).append(f"$line%n"))) | |
def parseLine(nextLine: String): DiaryConvert = | |
parseKey(nextLine) match { | |
case Some(newKey) => DiaryConvert(newKey, acc) // key change | |
case None => adder(this.currentKey, nextLine) // add | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment