Created
May 5, 2016 13:21
-
-
Save tOverney/ddbccdacb85adf09f97a9067ea7adcd9 to your computer and use it in GitHub Desktop.
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
package main.scala | |
object ResultsToHtmlItem extends App { | |
private def offset: Int => String = " " * _ | |
sealed trait HtmlElem { | |
def print(indent: Int): String = "" | |
} | |
case class DtDd(dtContent: HtmlElem, ddContent: HtmlElem) extends HtmlElem { | |
override def print(indent: Int): String = { | |
val indenta = offset(indent) | |
indenta + "<dt>\n" + dtContent.print(indent + 2) + indenta + | |
"</dt>\n" + indenta + "<dd>\n" + ddContent.print(indent + 2) + indenta + "</dd>\n" | |
} | |
} | |
abstract class Dl(content: List[HtmlElem]) extends HtmlElem { | |
override def print(indent: Int): String = { | |
val style = if (indent == 0) "" else """ style="margin-left: 5%;" """ | |
val indenta = offset(indent) | |
indenta + s"<dl$style>\n" + | |
content.map(_.print(indent + 2)).mkString + indenta + "</dl>\n" | |
} | |
} | |
case class InnerDl(content: List[HtmlElem]) extends Dl(content) | |
case class OuterDl(content: List[HtmlElem]) extends Dl(content) | |
case class StringLit(value: String) extends HtmlElem { | |
override def print(indent: Int): String = { | |
val indenta = offset(indent) | |
val sanValue = value.replaceAll(" – ", "<br>\n" + indenta) | |
indenta + sanValue + "\n" | |
} | |
} | |
case object Empty extends HtmlElem | |
val lines = scala.io.Source.fromFile("rawRes.txt").getLines().buffered | |
def consume: Unit = lines.next | |
implicit def string2StringLit(s: String): StringLit = StringLit(s) | |
def parse(current: Dl = OuterDl(Nil)): HtmlElem = if (lines.hasNext) { | |
val currLine = lines.head.stripMargin.trim | |
val endsWithColumn = currLine.endsWith(" :") | |
val containsColumn = currLine.contains(" :") | |
def toDtDd: DtDd = { | |
val Array(dt, dd) = currLine.split(" :").take(2) | |
val sanDt = dt + " :" | |
val sanDd = dd.drop(1) | |
DtDd(sanDt, sanDd) | |
} | |
current match { | |
case _ if currLine.isEmpty => | |
consume | |
parse(current) | |
case OuterDl(lst) if endsWithColumn => | |
consume | |
parse(OuterDl(lst :+ DtDd(currLine, parse(InnerDl(Nil))))) | |
case InnerDl(lst) if endsWithColumn => | |
InnerDl(lst) | |
case InnerDl(lst) if containsColumn => | |
consume | |
parse(InnerDl(lst :+ toDtDd)) | |
case _ => current | |
} | |
} else { | |
current | |
} | |
println(parse().print(0)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment