Last active
May 16, 2017 10:32
-
-
Save terjokhin/c7c27bf232828eea2798 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
object TestApp extends App { | |
trait Region { | |
val start: Int | |
val end: Int | |
def processRegion(input: String): String | |
} | |
case class Strong(start: Int,end: Int) extends Region { | |
override def processRegion(input: String): String = s"<strong>${input.substring(start, end)}</strong>" | |
} | |
case class Href(start: Int, end: Int) extends Region { | |
override def processRegion(input: String): String = s"""<a href="${input.substring(start, end)}">${input.substring(start, end).replaceFirst("http://", "")}</a>""" | |
} | |
case class Twitter(start: Int, end: Int) extends Region { | |
override def processRegion(input: String): String = s"""${input(start)}<a href="http://twitter.com/${input.substring(start + 1, end)}">${input.substring(start + 1, end)}</a>""" | |
} | |
trait Processor { | |
def process(input: String, list: List[Region]): String | |
} | |
class ProcessorImpl extends Processor { | |
override def process(input: String, list: List[Region]): String = { | |
val sorted = list.sortBy(-_.end) | |
processSorted(input, sorted) | |
} | |
private def processSorted(input: String, list: List[Region]): String = | |
if (list.nonEmpty) { | |
processSorted(processPart(input, list.head), list.tail) | |
} else { | |
input | |
} | |
private def processPart(input: String, region: Region): String = { | |
input.substring(0, region.start) + region.processRegion(input) + input.substring(region.end) | |
} | |
} | |
val proc = new ProcessorImpl | |
val region0 = Strong(14, 22) | |
val region1 = Strong(0, 5) | |
val region2 = Twitter(55, 67) | |
val region3 = Href(37, 54) | |
val input = """Obama visited Facebook headquarters: http://bit.ly/xyz @elversatile""" | |
println(input.zipWithIndex.toString()) | |
val result = proc.process(input, List(region0, region1, region2, region3)) | |
println(result) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment